0

Sorry if this is coming out as a silly question. I was using redux toolkit query in my project like this

const [trigger, result] = useLazyGetPostsQuery();

then in my component, I am using the data field inside the result to render my component in react. I have a button pressing on which the trigger method is called. It works fine for the first time. But for other times, an API call is made but the component does not re-renders. I have results from both calls inside the redux store but the component prefers the first one only. How can I make it so that only new results are used and old results are removed from the cache?

rest of the code for some more clarity

API

const postsApi = createApi({
  baseQuery: fetchBaseQuery({
    baseUrl: '/',
  }),
  tagTypes: ['Post'],
  endpoints: (build) => ({
    getPosts: build.query({
      query: (id) => ({ url: `post/${id}` }),
    })
  })
});

export { useLazyGetPostsQuery }  = postsApi;

Component

import { useLazyGetPostsQuery } from '../../service/posts'

const PostDetails = () => {
  const [trigger, result] = useLazyGetPostsQuery();
  const getNewPosts = userid => {
    trigger(Math.round(Math.random() * 10 + 1))
  }
  return (
   <>
   <button onClick={getNewPosts}>Click me!</button>
   {results.data.map(post => <div>{post.title}</div>)}
   </>
  )
}

CodeSandbox

Beginner
  • 182
  • 2
  • 14
  • 1
    They definitely are rerendering with the new value. Can you share a bit more code than just one line? Maybe you are logging it wrong in some way. – phry Jan 08 '22 at 18:02
  • [@phry](https://stackoverflow.com/users/2075944/phry) Thanks for the reply, I have added the code for better understanding. – Beginner Jan 08 '22 at 18:25
  • 1
    There seems to be nothing wrong with this. If you can rule everything else out, could you provide a full reproduction please? – phry Jan 08 '22 at 19:00
  • 1
    Sorry for the late response. While trying to replicate the problem in a sandbox so that I can share with you I found that there was an undefined check for the data from result. Every time new data from the query arrives the data field becomes undefined first and then new data is added to it by rtk query. Due to that undefined check my code was never processing the data that comes after that resulting in my problem. My problem is solved. And as you said it was problem with the code and not the rtk query. – Beginner Jan 08 '22 at 20:39

0 Answers0