React rtk query can't reconnect to socket server after page refresh

53 Views Asked by At

I am currently working on a chat app with the help of socket.io and rtk query, I followed rtk query docs to implement update in real time, evrything works fine until I refresh the page when doing it I know that the socket connection will be loose however aside from disconnection and logging again I can't get back the socket connection to my socket server. The socket server is written with the help of nestjs by the way.

First part I have a function that return me the socket, that function will initialize the socket or directly return it if, it exist already

import { io, Socket } from "socket.io-client";

export const getFriendsSocket = () => {
  const state: RootState = store.getState();
  console.log("entered");

  if (!socketFriends) {
    console.log("Before", { socketFriends, token: state.user.access_token });
    socketFriends = io("http://localhost:9000/friends", {
      auth: {
        token: state.user.access_token as string,
      },
      transports: ["websocket"],
      withCredentials: true,
    });
  }

  return socketFriends;
};

Then I use rtk query with onCacheEntryAdded to handle socket and initial query

 getAllReceivedFriendsRequest: builder.query<
      BaseServerResponse & {
        data: ServerResponseFriendReceivedRequestType[];
      },
      void
    >({
      query: () => ({
        url: "/friends/received-friends-request",
        method: "GET",
      }),
      async onCacheEntryAdded(
        _arg,
        { updateCachedData, cacheDataLoaded, cacheEntryRemoved }
      ) {
        try {
          const socket = getFriendsSocket();
          await cacheDataLoaded;

          socket.on(
            FriendEvent.FRIEND_REQUEST_RECEIVED,
            (
              data: SocketServerSucessResponse & {
                data: ServerResponseFriendReceivedRequestType;
              }
            ) => {
              console.log(data);

              updateCachedData((draft) => {
                draft.data.push(data.data);
              });
            }
          );
        } catch (error) {
          console.log(error);
        }
        await cacheEntryRemoved;
      },
    }),

and at the end in my component I call the useQuery hook with these parametes :

useGetAllReceivedFriendsRequestQuery(undefined, {
      refetchOnMountOrArgChange: true,
    });

so whenever I switch components the query will be made again however, although the query is made only the http part is done it seems like that the onCacheEntryAdded method is not called

0

There are 0 best solutions below