For my react-app/Express app I am trying to update the component state using the useEffects to run once when the component renders. Within useEffect I make a fetch to the express server.
const Favorites = ({ user }) => {
const loggedIn = user.loginname === "" ? false : true;
const [favs, setFavs] = useState([]);
useEffect(() => {
if (loggedIn) {
fetch(`/user/favs/${user.loginname}`)
.then((resp) => resp.json())
.then((data) => {
console.log(data);
setFavs([...data]);
console.log(favs);
});
}
}, []);
return (
<div className="mt-d d-flex justify-content-center">
{loggedIn ? (
<FavoritesList favs={favs} />
) : (
<h3 className="my-2">Please login to use this feature</h3>
)}
</div>
);
};
I make a fetch call on line 11 and am able to print the results on line 14. I then try to update the
component state using setFavs. My issue is that the state seems to not be updated or maybe
there is some async issue.
const FavoritesList = ({ favs, prop }) => {
const [data, setData] = useState([]);
useEffect(() => {
console.log(favs);
// favs.forEach(item => console.log(item))
}, []);
return <h5>Dummy component</h5>;
};
When I try to print favs on line 16 or print favs within the child(FavoritesList) component it is being passed down to, I get an empty array.