createAsyncThunk isn't changing state

So, i'am trying to create async thunk action, to mock data from file to the state.

import { createAsyncThunk, createSlice, PayloadAction } from '@reduxjs/toolkit';
import mocktasks from './mocktasks';

export interface TasksState {
  data: Task[];
}

const initialState: TasksState = {
  data: [],
};

export const fetchTasks = createAsyncThunk('tasks/fetchTasks', () => mocktasks);

export const tasksSlice = createSlice({
  name: 'tasks',
  initialState,
  reducers: {
    setTasks: (state:TasksState, action: PayloadAction<Task[]>) => ({
      ...state,
      data: action.payload,
    }),
    addTask: (state: TasksState, action: PayloadAction<Task>) => ({
      ...state,
      data: [...state.data, action.payload],
    }),
  },
  extraReducers: {
    [fetchTasks.fulfilled.name]: (state, action: PayloadAction<Task[]>) => ({
      ...state,
      data: action.payload,
    }),
  },
});

export const { setTasks, addTask } = tasksSlice.actions;

export default tasksSlice.reducer;

But there is a strange thing: even though, fetch actions have dispatched, my state hasn't changed. State and dispatched actions

I thought, that there was an issue with passing the payload to fetchTasks/fulfilled, but Redux devtools shows, that fulfilled has right data in payload, that is obtained from mock file:Action payload

UPD: even though, using dispatch(setTasks(mocktasks)) inside createAsyncThunk works just like i need.

Upvotes: 1

Views: 1206

Answers (2)

Rashomon
Rashomon

Reputation: 6792

Use builder notation to avoid typescript errors (official recomendation from redux-toolkit docs):

  extraReducers: (builder) => {
    .addCase(fetchTasks.fulfilled, (state) => ({
      ...state,
      data: action.payload,
    }))
  },

Upvotes: 1

timotgl
timotgl

Reputation: 2925

[fetchTasks.fulfilled.type] should work, as .name seems to always return the string actionCreator.

Upvotes: 0

Related Questions