Marco Ripamonti
Marco Ripamonti

Reputation: 247

Process fetched data - RTK Query / Redux toolkit / React

I'm new to all mentioned technologies and I'm trying to understand how should I operate in this scenario: I'm trying to fetch a CSV file from an API, once retrieved I want to process it to convert it in a json like object which then I can consume in one of my components. For instance, I want to view this data in a table and perform operations on this data which causes a change of state for that data.

From the documentation there is a transformResponse field for each endpoint defined which I could use to normalize data needed for my application:

const api = createApi({
  baseQuery: fetchBaseQuery({
    baseUrl: '/',
  }),
  tagTypes: ['Post'],
  endpoints: (build) => ({
    getPost: build.query<Post, number>({
      // note: an optional `queryFn` may be used in place of `query`
      query: (id) => ({ url: `post/${id}` }),
      // Pick out data and prevent nested properties in a hook or selector
      transformResponse: (response: { data: Post }) => response.data,
      ...

This could work but then I would have some confusion about how I can dispatch actions to change this state.

Another solution would use a Redux Toolkit store slice to save the fetched data and also perform the transform operation and dispatch actions.

Any help would be awesome!

Upvotes: 5

Views: 9479

Answers (1)

phry
phry

Reputation: 44078

RTK Query state is not meant to be state that is changed locally on the client - RTK Query is a pure cache.

It is meant for a workflow where you

  • fetch data from the server
  • display that data
  • send a request for changes to the server
  • get new data from the server
  • display that data again

The purpose of RTK-Query is to make that process as easy as possible for you and take over stuff like automatic re-fetching after something has been triggered to change on the server and removing old values from the cache.

If you want to keep data locally to do local changes on them, you should be using a traditional slice.

Upvotes: 10

Related Questions