Deadly_Smile's avatar

File object becomes en empty object when passing by Redux Toolkit

Hi, I am trying to pass a file to my back-end server from react front-end but whenever I pass the file by "reduxjs/toolkit/query/react", in the json payload that object becomes an empty object. This is my code:

editUser: builder.mutation({
        invalidatesTags: (result, error, arg) => {
          return [{ type: "user" }];
        },
        query: ({
          mobile,
          nid_card_number,
          country,
          district,
          address,
          document,
          name,
          date_of_birth,
          avatar,
          old_password,
          new_password,
          confirm_password,
          is_a_doctor,
        }) => {
          console.log(name, date_of_birth, avatar);
          return {
            url: "/edit-user",
            body: {
              mobile,
              nid_card_number,
              country,
              district,
              address,
              document,
              name,
              date_of_birth,
              avatar,
              old_password,
              new_password,
              confirm_password,
              is_a_doctor,
            },
            method: "PUT",
          };
        },
      }),

In the request the payload is always like this -

{"mobile":"","nid_card_number":"","country":"","district":"","address":"","document":null,"name":"New Me","date_of_birth":"2023-07-27","avatar":{},"old_password":"","new_password":"","confirm_password":"","is_a_doctor":""}

For now, I am only passing name,date_of_birth and avatar.

To test if there is any problem with my form page I logged at this line - console.log(name, date_of_birth, avatar);. It logs this -

New Me 2023-07-27 
File { name: "..jpg", lastModified: 1681413906094, webkitRelativePath: "", size: 293725, type: "image/jpeg" }

Is there something that I am missing?

0 likes
1 reply
MaxineAlban34's avatar
Level 1

Before passing the payload to the query, convert the File object to a serializable format, such as a Base64 string or a Blob object. You can use the FileReader API in JavaScript to read the file content and convert it to a Base64 string or a Blob. Once the File data is converted to a serializable format, include it in the payload. Now, the payload should only contain serializable data that can be safely transmitted through Redux Toolkit's query. When the payload reaches the server, handle the file upload separately from the regular form data. Depending on your server-side technology (e.g., Node.js with Express), you can use appropriate libraries or methods to handle file uploads. https://www.ballsportspro.com/ By following this approach, you can successfully pass the necessary data from your front-end to the back-end, including the file data, without running into serialization issues in Redux Toolkit.

Please or to participate in this conversation.