0

I have a React component for my project that fetches whether or not the user logs in with an Axios post request and fills a useState loginState variable that holds the username, then I am doing another post request to my backend using that username variable, and then I'm making a fetch api call using the data from the previous post request. I understand that these calls need to be made async, so that the next call has the updated state variable from the previous one, but for some reason when I am logging them in the console I get empty variables, and randomly I'll get the data and on refresh they are wiped once again.

function Favorites () {
    // console.log(login_State)
    const [loginState, setLoginState] = useState("");
    // const [favoriteID, setFavoriteID] = useState([]);
    // const [favResult, setFavResults] = useState();
    const [favArray, setFavArray] = useState();
    const [resultsData, setResultsData] = useState([]);


    const fetchFavorites = () => {
      fetch('https://api.spoonacular.com/recipes/644366/information?apiKey=06e9835a8c134d3e8add2752530a920b')
          .then(response => response.json())
          .then((data) => {
              setResultsData(Object.entries(data))
              // console.log("REAL SHIT: ", resultsData)
          });
        }
    const fetchFavArray = () => {
      Axios.post("http://localhost:3001/favorites", {
          username: loginState
        })
          .then((response) => {
            setFavArray(response.data)
            // console.log("FAV ARRAY: ", favArray)
          })
    } 


    useEffect(() => {
      Axios.get("http://localhost:3001/login").then((response) => {
        if(response.data.loggedIn === true){
          setLoginState(response.data.user[0].username)
        }
      })
      fetchFavArray();
      fetchFavorites();

      console.log(favArray)
      console.log(resultsData)


  }, []);
              


    // c2fa0d46b1eb4021943dad1c0672e6a2 

      return(
        //   <div className="favorites-wrapper">
        //     <h1> All of your favorites in one place! </h1>
        //     <div className="favorite-card">
        //     <Col className='mt-5' xs={6} md={4}>
        //       <Card className='card-hover'>
        //           <Card.Img fluid className='img' variant="top" src={resultsData[25][1]} />
        //           <Card.Body className='card-body'>
        //               <Card.Title className='title' >{resultsData[21][1]}</Card.Title>
        //               <Card.Text>
        //                   Some quick example text to build on the card title and make up the
        //                   bulk of the card's content.
        //               </Card.Text>
        //           </Card.Body>
        //       </Card>
        //   </Col>
        //   </div>
        // </div>
        <div></div>
)
}

I am new to react and am unsure how to use the previous updated state variables in the following function calls.

  • Call `fetchFavArray` and `fetchFavorites` inside your `if` block after setting the state. – Prerak Sola Mar 20 '23 at 22:15
  • 2
    React state updates are asynchronous - calling `setResultsData` only causes `resultsData` to have a different value on the next render, so logging (or otherwise using) it on the next line will always give you a "stale" value. See [this question](https://stackoverflow.com/questions/54069253/the-usestate-set-method-is-not-reflecting-a-change-immediately) for more on this. You should work with the value you're setting state to in the next `fetch` - which you can do by putting each `fetch` inside the `.then` of the previous one. Although it will look much neater with `async/await` instead. – Robin Zigmond Mar 20 '23 at 22:24
  • I've added fetchFavArrary to the .then of loginFetch, I added fetchFavorites to the .then of fetchFavArray, and I'm calling loginFetch() in useEffect, yet my states are still undefined/empty – Nick Pritchyk Mar 20 '23 at 23:01
  • The browser logs it by reference. 1s it will be empty, the next it would have updated. That is why it is console logging the result. To debug safely use JSON.parrse(JSON.stringify(favArray)) – Steve Tomlin Mar 20 '23 at 23:49

0 Answers0