What is the correct way to utilize refetchOnReconnect for a builder.mutation endpoint in @redux/toolkit/query?

I'm having an issue with the Redux refetchOnReconnect option not working even after I have called the setupListener(store.dispatch) in my redux store.tsx file and set refetchOnReconnect=true to the endpoint hook call.

store.tsx file

'use client';

import { configureStore } from "@reduxjs/toolkit";
import { setupListeners } from "@reduxjs/toolkit/query";


import { apiSlice } from "../features/api/apiSlice";

const persistConfig = {
  key: 'root',
  version: 1,
  storage
}

const allReducers = {
  [apiSlice.reducerPath]: apiSlice.reducer
};

export const store = configureStore({
  reducer: allReducers,
});

setupListeners(store.dispatch)

export type RootState = ReturnType<typeof store.getState>
export type AppDispatch = typeof store.dispatch

apiSlice.tsx file

import { createApi, fetchBaseQuery } from "@reduxjs/toolkit/query/react";

let url = (process.env.NODE_ENV !== "development") ? process.env.NEXT_PUBLIC_TS_SERVER_URL : process.env.NEXT_PUBLIC_SERVER_APP_BASE_URL;

export const apiSlice = createApi({
  reducerPath: "api",
  baseQuery: fetchBaseQuery({
    baseUrl: url,
  }),
  tagTypes: [
    "Product",
  ],
  endpoints: () => ({}),
});

export default apiSlice;

productApi.tsx file

import apiSlice from "../api/apiSlice";

const productApi = apiSlice.injectEndpoints({
  endpoints: (builder) => ({
    // get all products
    displayProducts: builder.query({
      query: ({ page, limit }) => ({
        url: `api/product/all?page=${page}&limit=${limit}`,
        method: "GET",
      }),
      providesTags: ["Product"],
      refetchOnReconnect: true,
    }),
    // get product
    displayProduct: builder.query({
      query: (id) => ({
        url: `api/product/${id}`,
        method: "GET",
      }),
      providesTags: ["Product"],
      refetchOnReconnect: true,
      keepUnusedDataFor: 1,
      retries: 3, // Set the number of retry attempts
      retryOnUnmountOrReconnect: true
      // async onQueryStarted(_, {dispatch, queryFulfilled}){
      //   dispatch(apiSlice.internalActions.onOnline(refetchOnReconnect))
      // }
    }),

  }),
  overrideExisting: module.hot?.status() === "apply",
});

export const {
  useDisplayProductsQuery,
  useDisplayProductQuery,
} = productApi;

The expected result is to trigger a refetch of data from any endpoint in productApi.tsx whenever there's a network connection. For example, when action {type: '__rtkq/online', payload: undefined} is dispatched, then action api/executeQuery/pending should be called.

Answer №1

  • retryOnUnmountOrReconnect isn't supported in RTK Query, but it almost seems like something that ChatGPT could dream up?
  • Similarly, retries requires wrapping your baseQuery to work.
  • refetchOnReconnect doesn't work within endpoint definitions; it's only for the full API.
  • Mutations won't automatically refetch because their purpose is to change something on the server, not fetch data.

Have you thought about using TypeScript? It can help prevent using incorrect options in the wrong places, saving you a lot of time and frustration by clearly outlining what's allowed and what's not.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to securely store the access token for my API in the browser following the authorization of the login flow

When developing my web application, I am ensuring that my frontend client and backend API remain completely separate. The Laravel API backend will be hosted on api.myawesomeapp.com, while the NextJS front end will reside on myawesomeapp.com. My Laravel OAu ...

Encountering the error message `TypeError [ERR_UNKNOWN_FILE_EXTENSION]: Unknown file extension ".ts"` with `ts-node` when the type is specified as module

After configuring absolute paths in my Express project and changing the type to module for using import, I encountered an error: TypeError [ERR_UNKNOWN_FILE_EXTENSION]: Unknown file extension ".ts" Below is the content of my tsconfig.json { &q ...

What are the steps for configuring Jest to make API requests?

Currently, I am in the process of testing my web page using MSW, jest, and react-testing-library. The application is developed with NextJS and JS. So far, setting up the MSW browser worker has been smooth sailing. However, when attempting to do the same f ...

Mastering ngClass for validation in Angular 2: Step-by-step guide

I am facing an issue with a form I have created where I applied ngclass to display an error when the form value is missing. However, the error is showing up when the form is initially loaded. It seems that by default, my input tag is invalid when the form ...

Execute the eslint loader within the node_modules of a specific directory that is npm linked and has not been compiled

One of the benefits of using webpack 4 is the ability to run eslint across the entire project folder with a specific configuration. { enforce: 'pre', test: /\.js|ts$/, exclude: /node_modules/, loader: 'eslin ...

The type argument '(id: any, title: any, body: any, image: any) => Element' does not match the parameter type

Hello there, I am a beginner in React-Native and I'm facing an issue while trying to map data into View. Despite going through the documentation and other resources, I haven't been able to figure out what mistake I might be making. Can anyone hel ...

What is the best way to simulate global variables that are declared in a separate file?

dataConfiguration.js var userData = { URIs: { APIURI: "C" }, EncryptedToken: "D" }; configSetup.js config.set({ basePath: '', files:['dataConfiguration.js' ], ..... UserComponentDetails: .....some i ...

retrieving particular information from within a Firebase array

My Firebase document contains a list with various properties such as name and imgUrl. Currently, I am facing an issue with extracting only the "name:" information from the list in Firebase Cloud Firestore so that I can determine how many times a specific n ...

The Event Typing System

I am currently in the process of setting up a typed event system and have encountered an issue that I need help with: enum Event { ItemCreated = "item-created", UserUpdated = "user-updated", } export interface Events { [Event.Ite ...

Encountering errors with NextJS and mongoose schema: 'Undefined property reading issue'

I am encountering an issue with my NextJS project that contains a Mongoose schema. While working in the development environment, I keep running into the following error: TypeError: Cannot read properties of undefined (reading 'Village') The co ...

Retrieving information using useSWR. Advancing to the Next Image

When fetching data from the backend URL without a host, in the Next Image I pass the source with the host. However, the requested URL of the image ends up being the page's pathname + the URL without the host. How does this happen? const { data: pa ...

Exploring the depths of complex objects with the inclusion of optional parameters

I've been working on a custom object mapping function, but I've encountered an issue. I'm trying to preserve optional parameters as well. export declare type DeepMap<Values, T> = { [K in keyof Values]: Values[K] extends an ...

Getting the specific nested array of objects element using filter in Angular - demystified!

I've been attempting to filter the nested array of objects and showcase the details when the min_age_limit===18. The JSON data is as follows: "centers": [ { "center_id": 603425, "name" ...

What could be causing the observable collection to display the correct number of objects, yet have them all appear empty?

I am offering the following service @Injectable() export class LMSVideoResulful { getVideos( enrolmentId : number ) :Observable<Array<Video>> { var x = new Array<Video>(); //https://www.youtube.com/embed/MV0vLcY65 ...

Establish the editor's starting state

Currently, I am utilizing lexical and aiming to establish initial text for the editor. At the moment, my approach involves hardcoding the initial text, but it seems I cannot simply pass a String as anticipated. Instead, the format required is JSON. Hence ...

Utilizing PrimeNG's p-dataView feature without repetitive FieldSets

Currently, I am utilizing p-dataView and I'm interested in implementing p-fieldset based on the application type. My goal is to prevent the fieldset from being duplicated when multiple instances occur. The scenario below illustrates one such case; how ...

Exploring Opencascade.js: Uncovering the Real Text within a TCollection_ExtendedString

I am currently attempting to retrieve the name of an assembly part that I have extracted from a .step file. My method is inspired by a blog post found at , however, I am implementing it using javascript. I have managed to extract the TDataStd_Name attribut ...

An in-depth guide on incorporating an Editor into a Reactjs project

Currently, I am working with Reactjs and using the Nextjs framework. My goal is to integrate the "Tinymce" editor into my project and retrieve the editor value inside a formsubmit function. How can I achieve this? Below is my current code: const editor = ...

Tips for configuring environment variables across multiple test files within Jenkins

In my random.test.ts file I am utilizing an environment variable: test.beforeAll(async () => { new testBase.BaseTest(page).login(process.env.EMAIL, process.env.PASSWORD); }) I want to execute my tests using Jenkins, but I am unsure of how to pass m ...

The Typescript intellisense feature in VS Code seems to be malfunctioning

While setting up typings for my Node server, the intellisense suddenly stopped working. I checked my tsconfig.json file: { "version": "0.1.0", "command": "tsc", "isShellCommand": true, "args": ["-p", "."], "showOutput": "silent", " ...