I am new to React. I am setting the state after fetching data from server. When I am trying to get that data from the state I am always getting null.
const [data, setData] = useState(dataObj);
const getData = () => {
//Fecthing data from server
setData(data);
}
useEffect(() => {
getData();
getDataDetails();
}
in getDataDetails()
I need the properties from state (data) which is always null.
const getDataDetails = () => {
console.log(data.empId);
}
How can make sure that state is always updated. How can I achieve it.
3
Answers
Try Updating your
useEffect
like this –[]
dependency array in useEffect will run the effect on component mount.Please go through the comment 1, 2, 3.
The main problem with the code here is that we are assigning the same data and not the new object to setData. it will not cause rerender.
This is a complete example of a useState in react with fetch