I am trying to useState to update the variables form the session storage, then I want to send an api request to my server and get some data. It all works if I hardcode in the email and password into the api request. But when I wait for the program to get the data the api request is running before the asynchronous useState function is finishing. I tried using useEffect and waiting for when user changes so that the function wouldn't run before it gets the data but that throws me into an infinite loop.
This is part of a broader program that takes the login data and authenticates. After that step i am looking to be able to move to a new page and then load in some data from my server but thats where it is breaking.
import axios from 'axios';
import Navbar from './Navbar';
import { UserContext } from './UserContext';
import React, { useContext, useState, useEffect } from 'react'
function Watchlist() {
const [user , setUser] = useState();
const [watchlist, setWatchlist] = useState();
setUser({
name: sessionStorage.getItem('sessionName'),
email: sessionStorage.getItem('sessionEmail'),
passowrd: sessionStorage.getItem('sessionPassword'),
authenticated: sessionStorage.getItem('sessionAuthenticated')
})
useEffect(() => {
getWatchlist()
}, [user])
function getWatchlist() {
console.log(`axios.post ${user.email} ${user.password}`);
axios.post(`/api/users/watchlist/id/${user.email}/${user.password}`).then((res) => {
if (res) {
setWatchlist(res.data);
console.log(JSON.stringify(res.data));
}
}).catch((err) => {
console.log(err);
})
}
return (
<div>
<Navbar />
<div>{JSON.stringify(watchlist)}</div>
</div>
)
} export default Watchlist;