Revalidate API data in real-time with SWR
An example usage of this may be a share dialog containing a list of users—when a new user is added to the dialog, we can broadcast an event telling other online users to refresh their user list.
A simple SWR hook that fetches a list of users may look similar to this:
To create a function that allows us to update this data in real-time, we can broadcast an event telling other clients to revalidate their data with useBroadcastEvent:
We can then listen for the event with useEventListener, and call the mutate function from SWR to update the data:
If we put everything together, we can display a list of users, broadcasting a revalidate event when a new user is added to the list.
Great, data that revalidates in real-time at the click of a button! You can find an example of this technique being used in the Next.js Starter Kit.