Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

181
Visualizações
Not getting updated state value in socket callback react native

I have listend an event in customhook and when that event works, I have to do some logic there with state.but now I only get empty array every time that event callback works.

const useChatHistoryList = () => {
  const sk = useSocket();
  const [chatList, setChatList] = useState([]);
  const [end, setEnd] = useState(true);

  useEffect(() => {
    sk.emit('chatlist');
  }, [start]);

 
  useEffect(() => {
    const onChatListReceived = data => {
      const _data = JSON.parse(data);
      setHistoryLoading(false);
      setChatList(_data);
    };

    const onChatListToUpdateReceived = data => {
      const _data = JSON.parse(data);
      console.log(chatList);//getting only empty array everytime
    };

    sk.on('chatlist', onChatListReceived);
    sk.on('chatlistToUpdate', onChatListToUpdateReceived);
    return () => {
      sk.off('chatlistToUpdate');
      sk.off('chatlist');
    };
  }, []);

  return { chatList,end};
};
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

Try to log your data first to make sure the data is there, then set your state with the data.

const [state, setState]= useState([]);

const _onReceived = (data) => {
  // Here is your data from socket
  console.log(data);

  // Then set state value with data
  setState(data);
}

useEffect(()=>{
  // Init socket listener
  socket.on("event", _onReceived);
}, []);

// This effect will runs everytime state value is set (including when setting default value)
useEffect(()=>{
  // Actual 'state' value
  console.log('State value: ', state);
}, [state]);

==========================

Edit, related to your updated codes in the question

Your onChatListToUpdateReceived function brings empty default value to the listener even later when it’s updated, your listener will still recognize chatList value as an empty string. Try to move out onChatListToUpdateReceived outside useEffect.

const onChatListToUpdateReceived = data => {
  const _data = JSON.parse(data);
  console.log(chatList);//getting only empty array everytime
};

useEffect(() => {
  const onChatListReceived = data => {
    const _data = JSON.parse(data);
    setHistoryLoading(false);
    setChatList(_data);
  };

  sk.on('chatlistToUpdate', onChatListToUpdateReceived);

  return () => {
    sk.off('chatlistToUpdate');
    sk.off('chatlist');
  };
}, []);

useEffect(() => {
  sk.off('chatlistToUpdate');
  sk.on('chatlist', onChatListReceived);
}, [chatList]);
about 4 years ago · Juan Pablo Isaza Relatório

0

I have not used socket.io before but this is what I meant by asynchronous update. From your code, it looked to me like your callback is getting called before the state is updated. So to solve this, I added a useEffect() with chatList as a dependency so that callback gets called every time chatList gets updated. I hope this makes sense.

const useChatHistoryList = () => {
  const sk = useSocket();
  const [chatList, setChatList] = useState([]);
  const [end, setEnd] = useState(true);

  const onChatListReceived = data => {
    const _data = JSON.parse(data);
    setHistoryLoading(false);
    setChatList(_data);
  };

  const onChatListToUpdateReceived = data => {
    const _data = JSON.parse(data);
    console.log(chatList); //getting only empty array everytime
  };

  useEffect(() => {
    sk.on('chatlist', onChatListReceived);
    sk.on('chatlistToUpdate', onChatListToUpdateReceived);
    return () => {
      sk.off('chatlistToUpdate');
      sk.off('chatlist');
    };
  }, []);

  // Emit chatlistToUpdate whenever chatList is updated
  useEffect(() => {
    sk.emit('chatlistToUpdate');
  }, [chatList]);

  return {
    chatList,
    end
  };
};

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda