I have app using React-Query, and I need to trigger data update after socket signal. That is, if I am on the user's page and I received a notification that the user's data has changed, then I need to send a request to receive updated data and write it. How to listen to socket events using useQuery hook?
Best Answer
You wouldn't do that with useQuery, but you would setup a socket subscription separately and then either write to the cache when you receive a message, or just invalidate the query to trigger a refetch.
I have a full blog post on this topic:https://tkdodo.eu/blog/using-web-sockets-with-react-query
But the gist is:
const useReactQuerySubscription = () => {const queryClient = useQueryClient()React.useEffect(() => {const websocket = new WebSocket('wss://echo.websocket.org/')websocket.onopen = () => {console.log('connected')}websocket.onmessage = (event) => {const data = JSON.parse(event.data)const queryKey = [...data.entity, data.id].filter(Boolean)queryClient.invalidateQueries(queryKey)}return () => {websocket.close()}}, [queryClient])}