Mr.Gomer
Mr.Gomer

Reputation: 649

React useEffect and useRef

so i got this useEffect function:

useEffect(
    () => {
      getDoH().then((response) => {
        initialResponse.current = response.data;
        console.log(response.data)
      }, (error) => {
        console.log(error);
      }); 
      console.log(initialResponse.current)
    }, []);

The getDoH is a axios.get function and the initialResponse is :

const initialResponse = useRef();

which im using to avoid some issues. The point is for the page to get a group of values from my backend on the first render and save it in the "initialResponse" so i can use it later in other functions.

but my

console.log(initialResponse.current)

keeps coming back as "Undfeined", in other words i cant seem to save me response value into it. any idea why or how to fix it ?

Upvotes: 0

Views: 1563

Answers (2)

samuei
samuei

Reputation: 2102

It looks like your problem statement isn't inside your .then() block, which means that you can't be certain that the .then() block has run yet by that time. Network calls are asynchronous, so Javascript charges ahead with execution instead of waiting. If you want to see what that value is after the call has returned, you should put your console.log(initialResponse.current) statement inside the .then() block.

Keep in mind that this means you won't necessarily have data there on first render. You should write your code to accommodate that possibility.

Upvotes: 1

You should make a validation of initialResponse before:

    useEffect(
        () => {
          if(initialResponse && initialResponse.current){
           getDoH().then((response) => {
            initialResponse.current = response.data;
            console.log(response.data)
           }, (error) => {
            console.log(error);
           }); 
           console.log(initialResponse.current)
          }
        }, [initialResponse, getDoH]);

And add initialResponse as a prop of the useEffect hook.

If you cant declare getDoH inside the useEffect, add it as a prop is a good practice.

Upvotes: 0

Related Questions