reduxjs / redux-toolkit

The official, opinionated, batteries-included toolset for efficient Redux development
https://redux-toolkit.js.org
MIT License
10.74k stars 1.18k forks source link

invalidatesTags is not refetching or trigging api #4679

Closed faizanibneadil closed 2 weeks ago

faizanibneadil commented 2 weeks ago

@gjastrab @praxxis @timdorr @jherr @pollen8

this is my store config

import { apis } from '@/services'
import { layoutSlice, statisticsSlice } from "@/store/slices"
import { combineReducers, configureStore } from '@reduxjs/toolkit'
import { setupListeners } from "@reduxjs/toolkit/query/react"
import { authSlice } from './slices/auth'

const rootReducer = combineReducers({
    [authSlice.name]: authSlice.reducer,
    [layoutSlice.name]: layoutSlice.reducer,
    [statisticsSlice.name]: statisticsSlice.reducer,
    [apis.reducerPath]: apis.reducer,
})

export const store = configureStore({
    reducer: rootReducer,
    devTools: true,
    middleware: (getDefaultMiddleware) => {
        return getDefaultMiddleware().concat(apis.middleware)
    },
})

setupListeners(store.dispatch)

// Infer the `RootState` and `AppDispatch` types from the store itself
export type RootState = ReturnType<typeof store.getState>
export type AppDispatch = typeof store.dispatch

this is my api config

import { Constants } from "@/constants"
import { RootState } from "@/store";
import { createApi, fetchBaseQuery } from "@reduxjs/toolkit/query/react"

export const apis = createApi({
    reducerPath: "apis",
    baseQuery: fetchBaseQuery({
        baseUrl: Constants.base_url,
        prepareHeaders: (headers, { getState }) => {
            const token = (getState() as RootState)?.auth?.user?.data?.token || localStorage.getItem("user") && JSON.parse(localStorage.getItem("user") || "")?.data?.token
            console.log("token", token)
            token && headers.set('Authorization', `Bearer ${token}`);
            return headers;
        },
    }),
    tagTypes: ["search", "statistics"],
    endpoints: (builder) => ({}),
})

these are my endpoints

import { Constants } from "@/constants";
import { apis } from "@/services";
import { toast } from "sonner";
import { IUploadJson, IUploadResponse } from "./upload.interface";

export const uploadApis = apis.injectEndpoints({
    endpoints: ep => ({
        uploadJson: ep.mutation<IUploadResponse, IUploadJson>({

            query: ({ file, players }) => {
                const formData = new FormData();
                formData.append("json_file", file);
                players?.forEach((player, idx) => formData.append(`player_fname[${idx}]`, player));

                return {
                    url: "/user/calculate_player_stats",
                    body: formData,
                    ...Constants.rtkCommonPostOptions,
                }
            },

            onQueryStarted(_, { queryFulfilled }) {
                queryFulfilled
                    .then(response => {

                        toast.success(response.data?.message || "File  uploade successfully and processed.")

                    })
                    .catch(response => toast.error(response.data?.message || "Something went wrong or maybe internal server error"))
            },

            invalidatesTags: ['statistics']

        }),
    })
})

export const {
    useUploadJsonMutation
} = uploadApis

import { apis } from "@/services";
import { IStatistics } from "./statistics.interface";
import { setOriginalStatistics, setPlayers, setStatistics } from "@/store/slices/statistics";
import { Utils } from "@/utils";

export const statisticsApis = apis.injectEndpoints({
    endpoints: ep => ({
        getStatistics: ep.query<IStatistics, void>({
            query: () => ({
                url: "/data",
                method: "GET",
            }),
            providesTags: ["statistics"],
            onQueryStarted(_, { dispatch, queryFulfilled }) {
                queryFulfilled.then(response => {
                    const originalStatistics = response.data
                    const statistics = Utils.transformTableData(response.data)
                    const players = Utils.getPlayersIds(response.data)
                    dispatch(setOriginalStatistics(originalStatistics))
                    dispatch(setStatistics(statistics))
                    dispatch(setPlayers(players))
                }).catch(error => {
                    dispatch(setOriginalStatistics([]))
                    dispatch(setStatistics([]))
                    dispatch(setPlayers([]))
                })
            },
        })
    })
})

export const {
    useGetStatisticsQuery
} = statisticsApis

i provided properly tags and properly invalidating but it is not invalidate the query

how can i fix...? any one have any solution...?

timdorr commented 2 weeks ago

The issue tracker here on GitHub is reserved for bug reports and feature requests. For usage questions (which is what I believe this is), please use our Discussions page, Stack Overflow, or Reactiflux where there are a lot more people ready to help you out. Thanks!

Please feel free to reply if you think this issue was closed prematurely.