1

I am trying to update the react state in functional component using API, However somehow it's not getting updated. I am not sure what is missing from my side. Can someone help what is missing in the below code snippet.

code

export default function Test(props) {
const [state, setState] = useState({
    data: []
  });

useEffect(() => {
  getConnectionUsers("Test")
  return () => {alert("component unmount");}
    }, [])
}

function getConnectionUsers(connection) {
    axios.get(URL).then((response) => {
        if (response.status === 200) {
          console.log(response.data);  // This is showing correct data which is coming from API
          setState({...state ,data:response.data});
          console.log(state.data);    //Empty State is coming which means somehow state is not updated properly
        }
    }).catch(error => {
        alert(error)
      });
}  
Drew Reese
  • 165,259
  • 14
  • 153
  • 181
Kanwal
  • 43
  • 2
  • 6
  • TL;DR React state updates are batched and asynchronous. React state is constant during the ***entire*** render cycle and only updated *between* render cycles. This means console logging state *right after* an enqueued updated will only ever log the *current* state from the *current* render cycle, not the enqueued state for the *next* render cycle. Use an `useEffect` hook with correct dependency to log state updates. – Drew Reese Dec 29 '20 at 07:07
  • React this.setState, and useState does not make changes directly to the state object. React this.setState, and React.useState create queues for React core to update the state object of a React component. So the process to update React state is asynchronous for performance reasons. That’s why changes don’t feel immediate. – Jazib Bashir Dec 29 '20 at 07:20

1 Answers1

1
export default function Test(props) {
  const [state, setState] = useState({
    data: []
  });

  useEffect(() => {
    getConnectionUsers("Test")
    return () => {alert("component unmount");}
  }, []);

  function getConnectionUsers(connection) {
    axios.get(URL).then((response) => {
        if (response.status === 200) {
          console.log(response.data);  // This is showing correct data which is coming from API
          setState({...state ,data:response.data});
          console.log(state.data);    //Empty State is coming which means somehow state is not updated properly
        }
    }).catch(error => {
        alert(error)
    });
  }  
}

You have to update your state in the lifecycle. And you can't touch useState outside of the function.

kyun
  • 9,710
  • 9
  • 31
  • 66