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

Assigning a dynamic name to an object in Typescript is a powerful feature

Is there a way to dynamically name my object? I want the "cid" value inside Obj1 to be updated whenever a new value is assigned. I defined it outside Obj1 and then called it inside, but when I hover over "var cid," it says it's declared but never used ...

What is the method to retrieve Response Headers in cases of an empty response?

Currently, I am working with Angular2 and dotcms. My goal is to retrieve response headers after making a call to subscribe. const httpOptions = { headers: new HttpHeaders({ 'Content-Type': 'application/json' }) .append('Access ...

Exploring the capabilities of google-diff-match-patch within the Angular framework

Seeking a way to incorporate the google diff/match/patch lib into an Angular application for displaying the variance between two texts. Here's how I plan on using it: public ContentHtml: SafeHtml; compare(text1: string, text2: string):void { var ...

Help! My layout got completely destroyed after adding the footer component to my NEXT.js page. How can I go about fixing this issue

<div>{children}</div> <Footer/> </body> </html> The addition of the Footer component caused chaos in my page layout Prior to integrating the footer component, everything was functioning smoothly. However, once I added ...

When using Angular forms, the password or username may be duplicated if entered twice when pressing the

I am currently working on a basic username and password form using Angular. Here's the template I have: <label class="welcome-content">Username:</label> <input #userName type="text" id="txtLoginUsername" (keyup.enter)="loginUser(userNa ...

What is the best way to transform a string array into a number array?

I'm attempting to convert a string array into a number array and after conducting some research online, I came across this solution: let numbersAsStringArray = originalQueryParams[property] ?? [] let numbers = numbersAsStringArray.map((i) => ...

Updating the text of a Mat-Label dynamically without the need to reload the page

In my application, there is a mat-label that shows the Customer End Date. The end date is fetched initially through a GET request to an API. Let's say the end date is 16-05-2099, which is displayed as it is. There is also a delete button implemented f ...

Is it possible to create an Angular 2 service instance without relying on the constructor method?

I'm struggling to utilize my ApiService class, which handles API requests, in another class. Unfortunately, I am encountering a roadblock as the constructor for ApiService requires an HttpClient parameter. This means I can't simply create a new i ...

Typescript navigation and Next.js technology

Currently, I am in the process of learning typescript and attempting to create a navigation bar. However, I encountered an error message stating "Unexpected token header. Expected jsx identifier". I am a bit puzzled by this issue. Could someone kindly pro ...

Managing incoming request data in React.js/Next.js

I'm facing an issue with integrating a payment system API in Poland. After fetching the data and receiving a token, I redirect to the payment website smoothly. However, upon successful payment, the payment system sends me data via URL. The problem li ...

Is implementing client components in Server Side pages an effective strategy for optimizing SSR performance?

In order to overcome the challenge of using client-side components in server-side pages, I made the decision to create a client-side wrapper to encapsulate these components within server-side pages. This way, I can manage all API calls and data fetching on ...

Discrepancy in user.uid between Frontend and Backend when using Next.js and Firebase

Embarking on my first web application project with Firebase and Next.js, I've encountered a puzzling issue. Here is a snippet of code I'm utilizing to create users on both Server-Side Rendering (SSR) and Client-Side Rendering (CSR) pages: export ...

What is the best way to format a text component so that the initial word in each sentence is bolded?

Creating a text component where the first word of the sentence is bold can be a bit tricky. The current solution may result in a messy output like "Tips: favouritevacation" where there is no space after "Tips:". This approach is not very elegant. One pos ...

In Next.js, the switch button remains in the same state even after the page is refreshed

Is there a solution for this issue? I am currently developing a switch button for a configuration page. The problem arises when I toggle the switch from active to maintenance mode, save it successfully, but upon refreshing the page, the switch reverts back ...

Redux state not reflecting changes until second click

My redux store has a simple boolean setup to track whether a sidebar is expanded or not. However, I'm encountering an issue where, even though the default value is false, clicking the toggle button outputs false first. Ideally, if it's initially ...

Next.js has shifted away from pre-generating page HTML

I have been working on a Jamstack application using Next.js, and I recently realized that the pages stopped pre-generating the HTML content without me noticing it at first. The pages still load fine, but there is no pre-generated HTML. Even the simplest c ...

What is the reason for Next.js passing static files as parameters in the URL?

Initially, I encountered the following error: Fetch API cannot load file:///xxxx/web-frontend/node_modules/axios/lib/core/createError.js. URL scheme must be "http" or "https" for CORS request. I was puzzled as to why this error occurred. Upon checking th ...

What is the process for defining the root of a project in ESLint?

I've been working on a project using Next.js and Typescript. My imports look like this: import Component from "/components/Component/Component";, with the root directory being specified as /src. This setup works fine in Next.js, but ESLint k ...

Sort the array by the elements in a separate array

Here is a filters array with three values: serviceCode1, serviceCode2, and serviceCode3. ['serviceCode1', 'serviceCode2', 'serviceCode3'] I have another array with approximately 78 records that I want to filter based on the a ...

Utilizing type maps within nested objects in Typescript: A comprehensive guide

Initially, a type is established that connects enum keys with specific types: enum MyEnum { A, B } type TypeMap = { [MyEnum.A]:string, [MyEnum.B]:number } interface ObjInterface<T extends keyof TypeMap> { obj: T, objData: Ty ...