I'm trying to fetch data from an API:
// Version.js const { REACT_APP_API_VERSION } = process.env; export default function getVersion() { let _version; fetch(REACT_APP_API_VERSION) .then(response => response.json()) .then(data => console.log(data)); return _version; // always returns undefined } how can I solve this problem?
Edit:
I solved it by returning a promise in the getVerion function then resolve that promise in the App.js with .then(...) and setState(...):
// version.js const { REACT_APP_API_VERSION } = process.env export default function getVersion() { return fetch(REACT_APP_API_VERSION) .then(response => response.json()) .then((data) => data[0]); } // App.js //... const [version, setVersion] = useState() useEffect(() => { getVersion().then((version) => setVersion(version)) }, []) //... https://stackoverflow.com/questions/66701318/how-to-return-data-after-fetch March 19, 2021 at 09:18AM
没有评论:
发表评论