Newly learning React. I am trying to run 2 async functions one after another. The first is to set State and the next one is an API call to fetch data from mongoDB. I need the first one to finish before executing the second because I want to make sure the state is updated correctly.
I thought adding await in front of the function call will solve the issue for me but it doesn't work.In my code, the 'user' value in the state is still not updated by the time the getBookShelf function call runs, and so I get an error on the getBookShelf call (the API call fails as the 'user' value in the body is null). How do I make this truly synchronous? What am I doing wrong?
const AuthProvider = ({ children }) => {
const [user, setUser] = useState(null);
const [userBookShelf, setUserBookShelf]= useState(null);
async function getBookShelf(userData) {
console.log("user", userData);
const response = await fetch(`http://localhost:5050/bookshelf/myBookShelf`, {method: "POST",
headers: {
"Content-Type": "application/json",
}, body: JSON.stringify({user:userData}),
});
if (!response.ok) {
const message = `An error occurred: ${response.statusText}`;
window.alert(message);
return;
}
const bookShelf = await response.json();
console.log("setting bookshelf", bookShelf);
setUserBookShelf(bookShelf);
}
const login = (userData) => {
const runSynchronously = async () => {
console.time("runSynchronously")
try {
await setUser(userData);
await getBookShelf(user);
} catch (error) {
console.log(error)
}
console.timeEnd("runParallelAll")
}
if (userData) {
runSynchronously();
}
localStorage.setItem('sessionToken', 'your-session-token');
};```