how to Automated Re-fetching data in RTK query

Viewed 1344

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' />}
        
        </>
    )
}
2 Answers

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

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.

Related