简体   繁体   中英

React state not updating after async await call

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();
}, []);

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM