简体   繁体   中英

How can I retrieve data (JSON) in React from the beginning and then export it as I wish in any other file of my app?

I need to have a file, let's say data.js . This file is going to fetch data with async/await fetch() from a MongoDB database. I would like to somehow pause the React execution until I have retrieved the data. Then start the React and export data to any file I wish. I am asking because it is like with async/await my app is executing in a "parallel" way so it seems impossible to assign a promise result in a variable in some point of my app like:

let data = {};
get_data().then((result) => (data = result));

It just keeps the data variable undefined.

There are various method by which you can do that.

  • First i guess let variable will only be in functional scope and can't get its value until return.

  • Second You can declare any setState in your code and use it by exporting that component anywhere you want.

  • Third is debouncing method in which you can make your function wait and then use that data in your UI.

if the result is coming undefiend then idk what you asking for. i wish this helps you.

 For debouncing const debounce = (func) => { let timer; return function (...args) { const context = this; if (timer) clearTimeout(timer); timer = setTimeout(() => { timer = null; func.apply(context, args); }, 500); }; }; const handleChange = (value) => { fetch(`https://demo.dataverse.org/api/search?q=${value}`).then((res) => res.json()).then((json) => setSuggestions(json.data.items)); }; const optimizedFn = useCallback(debounce(handleChange), []);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM