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. Here is my mutation code:

 addBanner: builder.mutation({ query(body) { return { url: `/api/banners`, method: 'POST', body, } }, }) 

Here is how I generate the data for request.

 const [addBanner, { isBannerLoading }] = useAddBannerMutation(); 
 const new_banner = new FormData(); new_banner.append("file", my_file); new_banner.append("type", my_type); new_banner.append("title", my_title); addBanner(new_banner).unwrap().then( () => ... 

But I get an error:

A non-serializable value was detected in the state, in the path: `api.mutations.L-Mje7bYDfyNCC4NcxFD3.originalArgs.file`... 

I know I can disable non-serializable check entirely through middleware, but I don't think it is an appropriate way of using Redux Toolkit and RTK. Without a file all works fine. Is there any right way of uploading files with RTK?

0

1 Answer

Edit: This has been fixed with @reduxjs/toolkit 1.6.1 - please update your package


I just opened an issue for this: - thanks for bringing it up!

For now, you'll probably have to disable that check (you can do so for a certain path in the state while keeping it for the rest with the ignoredPath option).

2

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like