Issue
I am currently working on the capstone for my course, but I have to use multiple async functions. I need to use AsyncStorage, SQLite storage, and fetching from a REST API. The issue I am encountering is when I have to fetch from the REST API and put it to state. I am not sure why, but it is only working the second time I load my app. I could be an issue with Expo, but I doubt it. I just need some help. Here is all the relevant code:
const [menuItems, setMenuItems] = useState();
const fetchMenuItemsFromAPI = async () => {
try {
const response = await fetch('https://raw.githubusercontent.com/Meta-Mobile-Developer-PC/Working-With-Data-API/main/capstone.json');
const json = await response.json();
setMenuItems(Object.values(json.menu));
} catch (e) {
console.error('Error:', e);
}
}
useEffect(() => {
fetchMenuItemsFromAPI();
},[])
I have no idea why it only loads the second time I load the app. If anyone has any feedback or can redirect me to a resource that will teach me asynchronous functions better than the course did, I would be infinitely thankful. Even the documentation for React Native says this is how you do it, so I am incredibly confused.
I have previously tried defining the function inside of the useEffect
hook, but that did not work. I think it is also worth noting that when I use things like: console.log(Object.values(json.menu))
, it prints exactly what I need it to print, but when I try setting that exact value into my setMenuItems()
, it just does not work the way I need it to.
Solution
From what I see in the code it should work, maybe the problem is not the status update but a problem rendering the new "menuItems" values. You could check if it is updating well the state when doing it for the first time with the following code, possibly it is updating well the value and the problem is the rendering of those values.
useEffect(() => {
console.log("Menu items value:", menuItems);
},[menuItems])
Answered By - Franco Mendo
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.