Gagan Rihal
Gagan Rihal

Reputation: 211

how to Automated Re-fetching data in RTK query

when i move next page or move to another page or update data ...data is not refetch ...when I reload the page then refetch data ...without reload how to refetch data using RTK query..

this is code

export const userService = createApi({
    reducerPath: 'userService',
    baseQuery: fetchBaseQuery({ baseUrl: 'http://localhost:5000/api/user/' }),
    tagTypes: ["Userdetail",'Profile_update'],
    endpoints: (builder) => ({
        getuserdetails: builder.query({
            query: () => ({
                url: 'userdetails',
                // method: 'GET',
                headers: {
                    'Content-type': 'application/json',
                    'auth-token': localStorage.getItem('loginToken')
                }
            }),
            providesTags : ['Userdetail']
        }),

        updateuserdetail: builder.mutation({
            query: (newbody) => {
                const {id,...data} = newbody
                return{
                    url: `profile_update/${id}`,
                    method: 'PUT',
                    body: data,
                    headers: {
                        'Content-type': 'application/json',
                        'auth-token': localStorage.getItem('loginToken')
                    }
                }
            },
            invalidatesTags :['Profile_update']
        }),
    })

})

call useGetuserdetailsQuery each component when render anothing to work

function ProtectedRouter(props) {
    const responseinfo  = useGetuserdetailsQuery({},{ refetchOnMountOrArgChange: true })
    const navigate = useNavigate()
    const { Component  } = props 
    const login = localStorage.getItem('loginToken')
    console.log(responseinfo)
    useEffect(() => {
        console.log('useeefect working')
        if (responseinfo.data) {            
            if (responseinfo.data.errormsg) {               
                if (responseinfo.data.errormsg.name === 'TokenExpiredError') {
                    localStorage.removeItem('loginToken')
                    navigate('/login',{state:{'logoutmsg':responseinfo.data.errormsg}})
                    navigate(0)
                }
            }
        }
    })
    
    return (
        <>
         {login? <Component /> : <Navigate to='/login' />}
        
        </>
    )
}

Upvotes: 3

Views: 14635

Answers (4)

leodev
leodev

Reputation: 1

This works for me.

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

const api = createApi({
  baseQuery: fetchBaseQuery({ baseUrl: '/' }),
  endpoints: (build) => ({
    getPost: build.query({
      query: () => 'post',
      keepUnusedDataFor: 0,
    }),
  }),
})

https://redux-toolkit.js.org/rtk-query/api/createApi#keepunuseddatafor

Upvotes: 0

Yilmaz
Yilmaz

Reputation: 49729

Your providesTags in query

 providesTags : ['Userdetail']

and invalidatesTags in mutation do not match.

invalidatesTags :['Profile_update']

that is why rtk is not re-fetching automatically.

providesTags will add a tag to the query. in your case useGetuserdetailsQuery is tagged with "Userdetail". Now whenever you make a mutation, you have to tell this mutation, which query you want it to be re-fetched. You tell this with invalidatesTags property. If you had this

invalidatesTags :['Userdetail']

After useUpdateUserDetail mutation run, this mutation would find the query with 'Userdetail' tag name, it would run that query again so your state and server are in sync.

Upvotes: 2

phry
phry

Reputation: 44336

Don't use localStorage.getItem('loginToken') inside your query, but pass it in as an argument. RTK Query will keep the cache value if the argument stays the same and it will do a new request if the argument changed.

Upvotes: 0

Danielprabhakaran N
Danielprabhakaran N

Reputation: 585

In the page where you are fetching the data using useGetuserdetailsQuery, Use this refetchOnMountOrArgChange: true. It will re-fetch the data when the component mount or its arguments are updated.

useGetuserdetailsQuery({}, { refetchOnMountOrArgChange: true })

This documentation will be helpful for you https://redux-toolkit.js.org/rtk-query/api/createApi

Upvotes: 6

Related Questions