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