Search code examples
reactjsrxjsreactive-programmingflux

How to force component render in React


I am making a simple ajax call to an API that produces data every 5 seconds, the data is received correctly using observables, and the data state is updated as expected. the problem is: the page is rendering only once when it is loaded, and not when date is changed using the setData function. if I reload the page by navigating to another link and then come back the data shows as expected her is the code:

function MyComponent() {

   const [data, setData] = useState(RxJSStore.getData())

   useEffect(() => {
       RxJSStore.addChangeListener(onChange);
       if (data.length === 0) loadDataRxJSAction()
       return () => RxJSStore.removeChangeListener(onChange)
   }, [data.length])


   function onChange() {
       setData(RxJSStore.getData())
   }

   return (
       <>
            <List data={data} />

       </>
   )
}

Solution

  • There is a way around this by forcing the component to render every time the onChange method is called. It is written in the documentation that this must only be used for testing purposes, but as the situation does not have another solution this might be the solution for this use case.

    import { useRefresh } from 'react-tidy'
    
     function MyComponent() {
    
     const [data, setData] = useState(RxJSStore.getData())
    const refresh = useRefresh()
    
    useEffect(() => {
       RxJSStore.addChangeListener(onChange);
       if (data.length === 0) loadDataRxJSAction()
       return () => RxJSStore.removeChangeListener(onChange)
    }, [data.length])
    
    
      function onChange() {
        setWarnings(RxJSStore.getWarnings())
        refresh()
    }
    
    return (
       <>
            <List data={data} />
    
       </>
     )
    }