2
const useChat = () => {
const [messages, setMessages] = useState([]); 
const socketRef = useRef();
const { chatId } = useSelector(state => state.chatin)
const { chatList } = useSelector(state => state.chatin)
const dispatch = useDispatch()

useEffect(() => {
   socketRef.current = io(socketClient);

 socketClient.on('chat', (data) => {
    const targetMessage = (messages) =>  messages.findIndex(item => item.message_number === data.message_number);
   console.log('targetMessage', targetMessage)
   if (targetMessage !== -1) {
     messages[targetMessage].is_hide = true;
   }
   setMessages((messages) => [...messages, data]);
 });


  return () => {
    socketRef.current.disconnect();
  };
}, []);

whenever I got new socket data, I wanna change 'messages' data, but can't access it, because it always shows initial data value.After that I have a question about how can I set it?

4
  • setMessages(data) , have you tried something like this? Commented Dec 27, 2020 at 15:40
  • Or are you trying to append the latest data into message state ? Not really sure what you meant by 'change messages' Commented Dec 27, 2020 at 15:43
  • did you try to log the data to see if you could get new data? Commented Dec 27, 2020 at 18:00
  • data is works, just 'messages' is not defined Commented Dec 28, 2020 at 3:57

1 Answer 1

1

You can move the if condition inside setMessages function, this way you will get access to the current state:

socketClient.on('chat', (data) => {
    setMessages((messages) => {
      const targetMessage = messages.findIndex(item => item.message_number === data.message_number);       
      if (targetMessage !== -1) {
        messages[targetMessage].is_hide = true;
      }
      return [...messages, data]
   });
 });
Sign up to request clarification or add additional context in comments.

1 Comment

it needs to be changed to const targetMessage = messages.findIndex(item => item.message_number === data.message_number); and works! thank you!

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.