React state created with useState doesn't update automatically when my API changes

Viewed 35

I have a problem when using the react useState states, the problem is that I want the state to update every time my api changes it's value, but the state just changes when the component is loaded, here is the code of the part that I'm having trouble with:

    const [partida,setPartida] = useState();

    const getNumero = ()=>{
        axios.get(`https://carta-rusa.herokuapp.com/routes/find/${localStorage.getItem('partidaId')}`)
        .then(res=>{
            setPartida(res.data.partida.jugadores.length)
        })
        .catch(err=>console.log(err));
    }
    useEffect(()=>{getNumero();},[])
1 Answers

If the endpoint at /routes/find/ returns different data at different times, you have 2 main options:

  • Easiest to implement, but not very elegant: Polling. Make a request to that endpoint periodically, like every 5 minutes or every 30 seconds or something.
useEffect(() => {
    const get = () => {
        axios.get(`https://carta-rusa.herokuapp.com/routes/find/${localStorage.getItem('partidaId')}`)
            .then(res => {
                setPartida(res.data.partida.jugadores.length)
            })
            .catch(err => console.log(err));
    };
    get();
    const intervalId = setInterval(get, 30000);
    return () => clearInterval(intervalId);
}, []);
  • More elegant solution: Have the server send the updated value instead. When the component mounts, establish a WebSocket connection with the server, and have the server send new data whenever it changes. On the client, listen for socket messages, and when a message is seen, update state as needed.
Related