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.