Search code examples
typescriptreact-reduxredux-toolkitrtk-query

Type void is not assignable to WriteableDraft


Does anyone know why I'm getting the following error?

Type 'void' is not assignable to type 'WritableDraft<Reminder>[]'.

I'm trying to create an async thunk to fetch data and store in state on app startup and I'm not sure why I'm having this in my extraReducers:

interface ReminderState {
  reminders: Reminder[];
}

const initialState: ReminderState = {
  reminders: [],
};

export const fetchReminders = createAsyncThunk("getReminders", async () => {
  await axios.get("http://localhost:3000/api/reminders")
  .then((response) => {
    return response.data.reminders;
  })
  .catch((err: Error | AxiosError) => {
    if (axios.isAxiosError(err)) {
      return err.response
    } else {
      return err;
    }
  })
});

export const reminderSlice = createSlice({
  name: "reminder",
  initialState,
  reducers: {
    setReminders: (state, action: PayloadAction<Reminder[]>) => {
      state.reminders = action.payload;
    },
    deleteReminder: (state, action: PayloadAction<string>) => {
      state.reminders = state.reminders.filter(
        (reminder) => reminder.id === action.payload
      );
    },
  },
  extraReducers: (builder) => {
    builder
    .addCase(fetchReminders.fulfilled, (state, action) => {
      state.reminders = action.payload;
    })
  }
});

export const { setReminders, deleteReminder } = reminderSlice.actions;

export default reminderSlice.reducer;

Solution

  • You need to return the value from payloadCreator of createAsyncThunk.

    payloadCreator is:

    A callback function that should return a promise containing the result of some asynchronous logic. It may also return a value synchronously.

    The function signature without return value is type fn = () => void; That's why you got the error.

    export const fetchReminders = createAsyncThunk("getReminders", async () => {
      // await axios.get("http://localhost:3000/api/reminders")
      
      return axios.get("http://localhost:3000/api/reminders")
        .then((response) => {
          return response.data.reminders;
        })
        .catch((err: Error | AxiosError) => {
          if (axios.isAxiosError(err)) {
            return err.response
          } else {
            return err;
          }
        })
    });