Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

145
Vistas
React: Load objects with a REST call and prepend new from WebSocket events

I want to implement a functionality that would load a list objects from a REST call when the page loads the first time and then it would consume new objects from WebSocket events and update/append them correspondingly.

const [objects, setObjects] = useState([])

useEffect(() => {
    axios.get(`${process.env.REACT_APP_REST_API}/objects`)
        .then(resp => setObjects(resp.data))
}, [])

const ws = new WebSocket(`${process.env.REACT_APP_WS_API}/objects`)
ws.onmessage = (event) => {
    const obj = JSON.parse(event.data)
    const items = [...objects]
    const index = items.findIndex((it) => it.id === obj.id)
    if (index === -1) {
        items.push(obj)
    } else {
        items[index] = obj
    }
    setObjects(items)
};

This code doesn't work. It opens WS connections several times. Also the initial data disappears from time to time and only the last object is shown. I understand, that it is related to the fact that react re-renders the component. And the issue with disappearing elements is most likely related to the scope of the closure used in the WS handler. At the same time, I have no idea how to solve it in React.

Q: How can I preload elements with a REST call and keep updating them further consuming events from WebSocket in a React component?

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

  • Try put ws creation into useEffect.
  • UseState with arrays is different.
  • If you like, use return on useEffect for closing ws when component will be unmount.
const [objects, setObjects] = useState([])

useEffect(() => {
axios.get(`${process.env.REACT_APP_REST_API}/objects`)
        .then(resp => setObjects(resp.data));

const ws = new WebSocket(`${process.env.REACT_APP_WS_API}/objects`)
ws.onmessage = (event) => {
    const obj = JSON.parse(event.data)
    
    const index = objects.findIndex((it) => it.id === obj.id)
    if (index === -1) {
        setObjects((current)=>[...current, obj]);
    } else {
        items[index] = obj
setObjects((current)=> current[index]= obj);
    }
   
};    

return () => { ws.close(); }

}, [])


about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda