So I have been re-iterating my code and working around with it for a few hours and I need help. My goal was to use useEffect
to load an API call from a horoscope API. I ran into this error where I was only able to see the data AFTER I loaded another page from the website and re-rendered the homepage. My goal was to see the data displayed initially on useEffect()
from when I called it. However, it seems to not work. Not sure if I need to use setInitialState, or manipulate the way I am exporting the values through context.
On further speculation, I somewhat see what the problem is in my code, but I have no idea HOW to use setInitialState to load values in from the api.
initialState.data.yesterday = data;
Do I save this to the a variable then call set data on that variable?
1.) I tried manipulating state best I could could.
2.) Page never loads data from API on first run, only shows data after I click a button
3.) Code seems to need setInitialDate
but can't find reasonable solution mixed with useEffect
to get the data right.
Thank you!!
I am willing to hear all optimal solutions for my problem. I am not even sure if I am going in the right direction. Thanks.
const [initialState, setInitialState] = useState({
data: {
yesterday: {},
today: {},
tomorrow: {},
}
});
useEffect(() => {
console.log("useEffect called");
// eslint-disable-next-line react-hooks/exhaustive-deps
async function getDayInfos() {
try {
const response = await axios.post('https://aztro.sameerkumar.website/?sign=aries&day=yesterday');
const data = response.data
initialState.data.yesterday = data;
} catch (error) {
console.error(error);
}
try {
const response = await axios.post('https://aztro.sameerkumar.website/?sign=aries&day=today');
initialState.data.today = response.data
} catch (error) {
console.error(error);
}
try {
const response = await axios.post('https://aztro.sameerkumar.website/?sign=aries&day=tomorrow');
initialState.data.tomorrow = response.data
} catch (error) {
console.error(error);
}
}
getDayInfos()
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [])
return <AstroContext.Provider value={{initialState}}>
{children}
</AstroContext.Provider>
}