So I was assigned to create a fairly simple dashboard with multiple React components which retrieve their information over an API and update correspondingly. Since all my components used models with a similar structure (as explained in the previous post), it was fairly easy to create a straight forward element to update them.
Auto Update Component
The auto update component has the following stub:
Of course you could do loads of fancy stuff to the component (e.g. error handling, etc), but its good enough for now! Let’s see what the props are:
url: API endpoint which returns the data.
interval: Interval in milliseconds to refresh data.
callback: A callback to be invoked as soon as the data has been fetched.
Inside any component you could now just embed the auto update component to take care of server queries:
Update State Automatically
You could go one step further and update the parent component’s state by providing it as the callback assuming that the data provided from the API server correspond to your component’s state. Consider that the API returns the following:
You can bind your components
setState function directly to the auto update component:
Note that you need to
setState so that it internally can access the component and not the auto update component!