0

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');
  };```
VS22
  • 1
  • 1
  • 1
    Does this answer your question? [The useState set method is not reflecting a change immediately](https://stackoverflow.com/questions/54069253/the-usestate-set-method-is-not-reflecting-a-change-immediately) – David Aug 12 '23 at 15:58
  • 2
    Trying to force asynchronous code to run synchronously is the wrong approach. You could use the useEffect hook to respond to state changes, or in this case if userData contains the value you need then why not pass userData to getBookShelf? – David Aug 12 '23 at 16:01

0 Answers0