How to send a file with RTK Query from Redux Toolkit?
Asked Answered
M

2

13

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?

Motorway answered 2/7, 2021 at 8:4 Comment(0)
M
7

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


I just opened an issue for this: https://github.com/reduxjs/redux-toolkit/issues/1239 - 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).

Mattern answered 2/7, 2021 at 8:45 Comment(2)
Thank you very much for your answer! I will use ignoredPath for now, but I hope we'll have a solution by the time we go production.Motorway
This has been fixed with @reduxjs/toolkit 1.6.1 - please update your packageMattern
B
0

pass formData in the query.

Like this:

 addBanner: builder.mutation({
          query(body) {
            return {
              url: `/api/banners`,
              method: 'POST',
              body,
              formData: true,
            }
          },
        })
Beyrouth answered 26/4, 2023 at 11:50 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.