0

I'm trying to get updated react hooks values inside socket on but it's not getting updated values. Whenever I update my react hook values it doesn't reflect inside socket. Below is my code

//socketIO in client 

useEffect(() => {

    const socket = socketIOClient(ENDPOINT);
    socket.on("FromAPI", data => {

      console.log(muteList); // here is my react hook 
    });


  }, []);

socket server sends update every 20 seconds. What can I do to get the updated react hook values inside socket

2
  • Depends on what you want to do inside the callback there, other than log the muteList Commented Dec 26, 2020 at 4:03
  • @CertainPerformance my program sends an alert based on data it receive and the exlusion list which is muteList hooks. The muteList is the list of items based on clicking of buttons. So I compare the muteList and data Commented Dec 26, 2020 at 4:19

1 Answer 1

1

If muteList happens not to be used for rendering, you can use a ref instead:

const muteListRef = useRef([]);

and change it with muteListRef.current = someNewMuteList.

If muteList is used for rendering, state is required. One option would be to re-add the listener every time the list changes:

const socketRef = useRef();
if (!socketRef.current) {
  socketRef.current = socketIOClient(ENDPOINT);
}
const [muteList, setMuteList] = useState([]);
useEffect(() => {
  const listener = (data) => {
    console.log(muteList);
    // do other stuff with muteList
  };
  socketRef.current.on('FromAPI', listener);
  // Remove this listener whenever the component unmounts
  // or whenever muteList changes
  return () => socketRef.current.off('FromAPI', listener);
}, [muteList];

You could also use both a ref and state to solve the problem, but that isn't a very elegant approach.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.