0

I am trying to create a player, using a POST request but getting the error as promise rejected in redux devtool.

But I can see the data on the UI. I am using createAsyncThunk and createEntityAdapter:

createAsyncThunk

export const addPlayer = createAsyncThunk(
  'players/addPlayer',
  async (formData) => {
    await fetch('/api/players', {
      headers,
      method: 'POST',
      body: JSON.stringify(formData),
    });
    await response.json();
    console.log(formData);

    return formData;
  }
);

extraReducers builder

 .addCase(addPlayer.fulfilled, (state, action) => {
        adapter.addOne(state, action.payload);
      })

handler

 case 'POST': {
      const player = await controller.create(req.body);
      return res.status(201).json(player);
    }

SubmitfromFunction

const handleSubmitData = (event) => {
    event.preventDefault();
    //fix this validation later
    if (!formData) {
      alert('Please fill from');
    } else {
      dispath(addPlayer(formData));
      // window.location.reload();
      console.log(formData);
    }
  };

screenshot of Redux Devtool:

error code

The framework I am using is NextJs here. Does anyone know what am I missing or doing wrong?

James Z
  • 12,209
  • 10
  • 24
  • 44
Tapesh Patel
  • 131
  • 1
  • 17

1 Answers1

1

You are missing a const response = in your thunk - and you have to assing the json result to a variable as well

export const addPlayer = createAsyncThunk(
  'players/addPlayer',
  async (formData) => {
    const response = await fetch('/api/players', {
      headers,
      method: 'POST',
      body: JSON.stringify(formData),
    });
    const json = await response.json();

    // this logic will always return `undefined` but I have no idea what you actually want to do here
    return formData && console.log(json ? true : false);
  }
)

phry
  • 35,762
  • 5
  • 67
  • 81
  • Hi sorry I added the error code, also I updated the code in the post please let me know if anything missing. And I am trying to create a record useing `fromData` object which holds by updated records and then `create by using the `addOne` adapter from redux toolkit – Tapesh Patel Jul 14 '22 at 14:49
  • Hi @phry thanks a million the const part was missing due to which my request was not fulfilled and now the error has been resolved. thanks a million for the suggetion – Tapesh Patel Jul 14 '22 at 14:55