React Signalr Access State Variable

Viewed 634

So I am trying to update my state when a new message comes in from signalr, but when console log the state variable, its empty.

const [posts, setPosts] = useState([]);

useEffect(() => {
  const results = await myApiCall();

  setPosts(results);
}, []);

useEffect(() => {
  websocket.connection.off(‘OnPostCreated’, (data) => {
    console.log(posts);
  });

  websocket.connection.on(‘OnPostCreated’, (data) => {
    console.log(posts);
  });

}, [posts]);

The response I get from the console log is an empty array. I know posts is not empty as I see the posts on my page. If I replace the console log with setPosts(data), it replaces all the posts with the one coming back from signalr. Thoughts on why inside the on callback that posts is showing empty vs being populated? Thanks

2 Answers

Not a solution but a workaround I used when I encountered this issue. I am still looking for a proper solution.

You can use a separate state variable and update it in the handler callback. In this case the previous state does not matter since you're only updating the variable and not accessing it in the callback. A useEffect can then be used to track this change and make the necessary changes to the posts array which should include the data you set earlier.

const [posts, setPosts] = useState([]);
const [newPostReceived, setNewPostReceived] = useState();

useEffect(() => {
  const results = await myApiCall();
  setPosts(results);
}, []);

useEffect(() => {
  // check for undefined
  if(newPostReceived){
    let newPosts=[...posts, newPostReceived]
    setPosts(newPosts);
  }
}, [newPostReceived]);

useEffect(() => {
  websocket.connection.off(‘OnPostCreated’, (data) => {
    console.log(posts);
  });

  websocket.connection.on(‘OnPostCreated’, (data) => {
    setNewPostReceived(data);
  });

}, [posts]);
Related