最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Why is react state(array) empty inside callback function? Why is it not using the updated value from outer scope? -

programmeradmin1浏览0评论

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
Add a ment  | 

2 Answers 2

Reset to default 4

Try 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//)

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论