Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

134
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!