4

I am using React Hooks and the useEffect to get data from an API. I need to make 2 consecutive calls. If I console.log the response directly, it shows the correct response, but when I console.log the state, its empty and its not updating. What am I doing wrong?

const [describeFields, setDescribeFields] = useState([]);

useEffect(() => {
const fetchData = async () => {
  await axios
    .all([
      axios.get("someUrl"),
      axios.get("someotherUrl")
    ])
    .then(
      axios.spread((result1, result2) => {
        console.log(result1.data.result.fields); //shows correct response
        setDescribeFields(result1.data.result.fields);
        console.log(describeFields);  //shows empty array      
      })
    );
};
fetchData();
}, []);
Shubham Verma
  • 4,918
  • 1
  • 9
  • 22
Besart Marku
  • 543
  • 1
  • 7
  • 14

1 Answers1

2

It will not be displayed just after that if you want to see latest changes just console log before return statement as setState is async your console.log run before then setState

const [describeFields, setDescribeFields] = useState([]);

useEffect(() => {
const fetchData = async () => {
  await axios
    .all([
      axios.get("someUrl")
      axios.get("someotherUrl")
    ])
    .then(
      axios.spread((result1, result2) => {
        console.log(result1.data.result.fields); //shows correct response
        setDescribeFields(result1.data.result.fields);
      })
    );
};
fetchData();
}, []);

console.log(describeFields); //Check here
return(

)


Note : [] array in useEffect means it will run only one time. If you want to update as long as variable changes then add it as dependency.

Here is working example : https://codesandbox.io/s/prod-thunder-et83o

Shubham Verma
  • 4,918
  • 1
  • 9
  • 22