Cannot Parse Form Data in NextJS project - Promise cannot be resolved

32 Views Asked by At

I am trying to parse Form Data via Formidable package in my NextJS v13 project. Here is the code for it:

Client side:

// lib/courses.js 
import { mainApi } from '.';

export const coursesApi = mainApi.injectEndpoints({
  reducerPath: 'coursesApi',
  tagTypes: ['Courses'],
  endpoints: (builder) => ({
    getCourses: builder.query({
      query: () => ({
        url: 'courses',
        method: 'GET'
      }),
      providesTags: ['Courses'],
    }),
    getCourseById: builder.query({
      query: ({ id }) => `courses/${id}`,
      providesTags: ['Courses'],
    }),
    createCourse: builder.mutation({
      query: ({ data }) => ({
        url: `courses`,
        method: 'POST',
        body: data,
      }),
      invalidatesTags: ['Courses'],
    }),
    updateCourse: builder.mutation({
      query: ({ courseId, data }) => ({
        url: `courses/${courseId}`,
        method: 'PUT',
        body: data,
      }),
      invalidatesTags: ['Courses'],
    }),
  }),
});

export const {
  useGetCoursesQuery,
  useGetCourseByIdQuery,
  useUpdateCourseMutation,
  useCreateCourseMutation,
} = coursesApi;

Component where the form is being filled and request to the server is sent:

// create-course-component
...
const response = await createCourse({ data: formData })
...

Back-End code:

...
    console.log('Request: ', req)
    const data: any = await new Promise((resolve, reject) => {
      const form = new IncomingForm();
      console.log('Before form parse')
      form.parse(req, (err: any, fields: any, files: any) => {
        console.log('Inside form parse')
        if (err) reject({ err });
        resolve({ err, fields, files });
      });
      console.log('After form parse')
    });
    console.log('Outside promise')
...

It seems that it is STUCK within the Promise. Here is what I get in the console: enter image description here

As you can see, Form Data inside the request body looks PERFECTLY fine, but for some reaon the promise is not resolved and it goes into an endless loop I guess.

Any idea why this is happening?

0

There are 0 best solutions below