Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

235
Vistas
How to update returned hook data from RTK Query when a websocket message is received

Please can someone explain how to wire up the receiving of data in a websocket message to the data object of the hook from an RTK Query api endpoint?

We don't need to store the message that is received, we just want to pass it on in the data argument of the useGetWebsocketResponseQuery hook so we can trigger a notification in the UI.

reducerPath: 'someApi',
    baseQuery: baseQueryWithReauth,
    endpoints: (builder) => ({
        getWebsocketResponse: builder.query<WebsocketResult, void>({
            queryFn: () => ({data: {}),
            async onCacheEntryAdded(arg, { updateCachedData, cacheDataLoaded, cacheEntryRemoved }) {        
                try {                  
                    // wait for the initial query to resolve before proceeding
                    await cacheDataLoaded;

                    const socket = io('http://url', {});                
                    socket.on('connect', () => {
                        console.log('socket connected on rtk query');
                    });

                    socket.on('message', (message) => {
                        console.log(`received message: ${message}`);
                        // THIS IS WHERE THE DATA NEEDS TO BE WIRED UP TO THE HOOK BUT HOW?
                    });

                    await cacheEntryRemoved;        
                } catch {
                    // no-op in case `cacheEntryRemoved` resolves before `cacheDataLoaded`,
                    // in which case `cacheDataLoaded` will throw
                }                 
            }
        }),
// Export hooks for usage in functional components, which are
// auto-generated based on the defined endpoints
export const {
    useGetWebsocketResponseQuery
} = someApi;

It feels like this should be possible in the socket.on('message', {}) handler but how? The updateCachedData method seems like it should be the way to go but I am not sure how to implement it.

All help gratefully received :-)

Much thanks,

Sam


UPDATE with solution from @phry

The issue was that the data defined in the queryFn needed to match the shape of what was appended from the cacheDataLoaded i.e. it should be like this:-

queryFn: () => ({data: { messages: [] }),

and

socket.on('connect', () => {                        
   updateCachedData((currentCacheData) => {
      currentCacheData.messages.push(message);
   });
});
about 4 years ago · Juan Pablo Isaza
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda