RTKQ: File Uploading

See original GitHub issue

I use queryFn parameter to send multipart/form-data:

endpoints: (build) => ({
  uploadFile: build.mutation({
    async queryFn(file, _queryApi, _extraOptions, fetchWithBQ) {
      // upload with multipart/form-data
      const formData = new FormData();
      formData.append('file', file);
      const response = await fetchWithBQ({
        url: '/files',
        method: 'POST',
        body: formData,
      }, _queryApi, _extraOptions);
      if (response.error) throw response.error;
      return response.data ? { data: response.data } : { error: response.error };
    },
  }),
}),

It works totally correct, but I have arguments serialization error in console:

[Error] A non-serializable value was detected in the state, in the path: `api.mutations.EB07i6POmA2Xe9YPh5gpb.originalArgs`. Value: (2)
File {name: "message_saved.mp3", lastModified: 1625855746000, webkitRelativePath: "", size: 46478, type: "audio/mpeg", …}
"
Take a look at the reducer(s) handling this action type: api/executeMutation/rejected.
(See https://redux.js.org/faq/organizing-state#can-i-put-functions-promises-or-other-non-serializable-items-in-my-store-state)"
	(anonymous function) (main.js:5794)
	measureTime (main.js:5553)
	(anonymous function) (main.js:5789)
	(anonymous function) (main.js:5717)
	(anonymous function) (main.js:6546)
	step (main.js:5447)
	rejected (main.js:5486)
	promiseReactionJob

I tried to overwrite serializeQueryArgs option in createApi but it doesn’t help. Can’t even catch that request over there. It’s weird that I see other GET requests inside serializeQueryArgs, but not that POST file mutation.

serializeQueryArgs: (args) => {
  const { endpointName, queryArgs } = args;
  // try to overwrite uploadFile endpoint serialization
  if (endpointName === 'uploadFile') {
    const { lastModified, name, size, type } = queryArgs;
    const payload = JSON.stringify({
      lastModified, name, size, type,
    });
    return `${endpointName}(${payload})`;
  }

  // Sort the object keys before stringifying, to prevent useQuery({ a: 1, b: 2 }) having a different cache key than useQuery({ b: 2, a: 1 })
  return `${endpointName}(${JSON.stringify(queryArgs, (key, value) =>
    isPlainObject(value)
      ? Object.keys(value)
          .sort()
          .reduce((acc, key) => {
            acc[key] = value[key]
            return acc
          }, {})
      : value
  )})`;
},

Package version: "@reduxjs/toolkit": "^1.6.0"

Issue Analytics

  • State:closed
  • Created 2 years ago
  • Comments:5 (3 by maintainers)

github_iconTop GitHub Comments

1reaction
markeriksoncommented, Jul 18, 2021
1reaction
phryneascommented, Jul 17, 2021

See #1318

You can already install it and try it following this link (contains instructions for npm and yarn): https://ci.codesandbox.io/status/reduxjs/redux-toolkit/pr/1318

Feedback welcome.

Read more comments on GitHub >

github_iconTop Results From Across the Web

How to send a file with RTK Query from Redux Toolkit?
I am trying to use RTK Query mutations to upload a file to the API. ... Is there any right way of uploading...
Read more >
React + RTK Query + Material UI - Image Upload - CodevoWeb
In this article, you'll learn how to upload images with React, RTK Query, Redux Toolkit, Zod, React Hook Form and Material UI.
Read more >
Redux Essentials, Part 8: RTK Query Advanced Patterns
The official Redux Essentials tutorial: learn advanced patterns for fetching data with RTK Query.
Read more >
Creating React Apps With Redux Toolkit and RTK Query - Toptal
There are many file changes introduced in this step. I encourage you to dig into the parts that you are interested in.
Read more >
React Redux Tutorial - File & Image Uploading - YouTube
https://www.turbo360.coQuick demonstration showing up to upload images and other static assets via React, Redux and the Turbo CDN ...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found