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

本文标签: