A problem here š
I have this code inside a functional component:
const [fact, setFact] = useState();
useEffect( () => {
async function startGetCatFact () {
const {fact:factFromApi} = await getCatFact();
setFact(factFromApi);
}
startGetCatFact();
return
},[])
const queryWords = fact.split(' ').slice(0, 3); //fact is not defined error
But there’s a problem here that I can’t understand:
When I execute this code I get an error that says that "fact" is not defined.
UseEffect should set my state fact and I should be able to use it after using the useEffect but I get the undefined all the time.
Pretty sure this is about asynchronous process and stuff but I can’t find a solution.
Any thoughts?
3
Answers
it’s very straightforward – when the code first gets uploaded, way before the useEffect runs – the ‘fact’ variable has no value, so it crashes.
the hook useEffect is basically the same as componentDidMount, so it only runs after the component mounted already – which means the code that uses the ‘fact’ variable first takes it’s value from the initial state you’re giving it when you’re defining it.
to create an easy fix you can just give it a value in the use state and when the component will mount – that value will change to whatever you do set it to in the useEffect
create your function outside of useEffect and call inside
so in that way u will fully control the loading stage.
replace this:
with:
It(?) will to check variable on first render and when the variable is available it will use the variable