Search code examples
reactjsreduxreact-routerredux-toolkitrtk-query

How to update fetched data in redux toolkit query?


I am using redux-toolkit-query for API calls. Using its createAPI method I created following

export const postApi = createApi({
  reducerPath: 'posts',

  baseQuery: query({
    baseUrl: 'https://localhost:3000/posts/',
  }),

  endpoints: build => ({
    getAllPosts: build.query({
      query:() => ({ url: `/all`, method: METHOD_GET })
    }),
    getPost: build.query({
      query: id => ({ url: `/${id}`, method: METHOD_GET })
    }),
  }),
});

sample API response:

{
 "user_name": "json",
 "user_id": 2313,
 "posts": [
  {
    "title": "Post a",
    "post_id": 1
  },
  {
    "title": "Post b",
    "post_id": 2
  },
 ]
}

Now both getAllPosts and getPost methods work, but what I was doing was that from getAllPosts is was iterating through all posts and rendering them. My aim was to have a refresh button on each post pressing which will refresh the data for that post only. And this is where I am getting a hard time. I don't know what's the best way to approach this.

It will be a great help if you guys can point me in the right direction. Not asking for code just the approach.

Thank you for help :)


Solution

  • I would suggest following steps:

    1. Fetch the posts with getAllPosts via useGetAllPosts

    2. Iterate over result items, creating the Post component whatever it should look like, and passing post's id into it. Or the whole post object, up to you.

    3. In the Post component call the useGetPost, providing the id, props, from the parent PostsList component

    4. In the Post component define a "refresh" button with the handler, which will call refetch function, provided by the useGetPost hook:

      const {data, refetch} = useGetPost(postId);
      

    that's it. By calling refetch you'll get the most up-to-date data from API, ignoring the cache.

    There are other approaches with the Tags, cache invalidation, but I guess this one will work for your case.