skip to Main Content

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


  1. 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

    Login or Signup to reply.
  2. create your function outside of useEffect and call inside

    const [fact, setFact] = useState();
    const [loading,setLoading] = useState(true);
    const startGetCatFact = async () => {
      const {fact:factFromApi} = await getCatFact();
      setFact(factFromApi);
      setLoading(false)
    }
    
    useEffect( () => {
        startGetCatFact();
      },[])
    
    if(!loading){
      const queryWords = fact.split(' ').slice(0, 3);
    }
    

    so in that way u will fully control the loading stage.

    Login or Signup to reply.
  3. replace this:

    const queryWords = fact.split(' ').slice(0, 3);
    

    with:

    const queryWords = fact?.split(' ').slice(0, 3);
    

    It(?) will to check variable on first render and when the variable is available it will use the variable

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search