admin管理员组文章数量:1394167
This problem has stumped me. I'm trying to append values to existing array, but inside the onmessage callback, state is an empty array every time the callback is called! I'm not able to figure out why! Any help is appreciated.
- React version: 16.12.0
- Node version: 10.16.3
Code snippet:
const Example = () => {
const [state, setState] = useState([]);
useEffect(() => {
axios.get("/data").then((resp) => setState(resp.data)); // Array of length of 50
const eventSource = new EventSource("/event");
eventSource.onmessage = (e) => {
console.log(state); // [] - Empty array
const data = JSON.parse(e.data);
setState([data, ...state]); // End result - state is array of length 1
}
return () => eventSource.close();
}, []);
console.log(state); // Array of length 50
// Table rendered with 50 elements
return <Table data={state} />
}
Thanks
This problem has stumped me. I'm trying to append values to existing array, but inside the onmessage callback, state is an empty array every time the callback is called! I'm not able to figure out why! Any help is appreciated.
- React version: 16.12.0
- Node version: 10.16.3
Code snippet:
const Example = () => {
const [state, setState] = useState([]);
useEffect(() => {
axios.get("/data").then((resp) => setState(resp.data)); // Array of length of 50
const eventSource = new EventSource("/event");
eventSource.onmessage = (e) => {
console.log(state); // [] - Empty array
const data = JSON.parse(e.data);
setState([data, ...state]); // End result - state is array of length 1
}
return () => eventSource.close();
}, []);
console.log(state); // Array of length 50
// Table rendered with 50 elements
return <Table data={state} />
}
Thanks
Share Improve this question asked Dec 13, 2019 at 11:48 Sagar B HathwarSagar B Hathwar 5367 silver badges18 bronze badges 1- Same question here !! In my case the it was a object {} instead a array the solution @atin-singh worked. – fct Commented Mar 25, 2021 at 20:35
2 Answers
Reset to default 4Try using the state updater function. If you pass a function to setState, React will call it with the actual state:
setState(actualState => {
return [data, ...actualState]
});
Setting a state is async in nature. Your console.log will always print the previous value of state. You can use useEffect to get the updated value of state everytime it changes -
useEffect(() => { console.log("value of state is", state)}, [state] // dependancy array//)
本文标签:
版权声明:本文标题:javascript - Why is react state(array) empty inside callback function? Why is it not using the updated value from outer scope? - 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744622123a2616090.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论