Search code examples
reactjstypescriptreduxredux-toolkit

How to create a redux store?


I'm following this tutorial on react-redux but I'm stuck.

When I try to configureStore I get the error Property 'reducer' does not exist on type 'Reducer<Winner>'

Here is the store:

store.ts

import { configureStore } from "@reduxjs/toolkit";
import winnerSlice from "./winnerSlice";

const store = configureStore({
  reducer: {
    winners: winnerSlice.reducer,
  }
})

export type RootState = ReturnType<typeof store.getState>

export type AppDispatch = typeof store.dispatch

export type AppStore = typeof store

And here is the winnerSlice.ts:

import { createSlice, PayloadAction } from '@reduxjs/toolkit';
import { RootState } from './store';

interface Winner {
  name: string
}

const initialState: Winner = {
  name: "",
}

export const winnerSlice = createSlice({
  name: 'winner',
  initialState,
  reducers: {
    setWinner: (state, action: PayloadAction<string>) => {
      state.name = action.payload
    },
    clearWinner: (state) => {
      state.name = ""
    }
  }
})

export const { setWinner, clearWinner } = winnerSlice.actions

export const selectWinner = (state: RootState) => state.winners.value // This line is also erroneous by the way 

export default winnerSlice.reducer

I need a hint on how to configure the store. The example in the documentation is incomplete. These are simply not defined so I'm stuck:

posts: postsReducer,
comments: commentsReducer,
users: usersReducer,

Solution

  • The winnerSlice reducer is the default export.

    export default winnerSlice.reducer
    

    Update the store creation to use the correct reducer value, e.g. just the default import.

    Example:

    store.ts

    import { configureStore } from "@reduxjs/toolkit";
    import winnersReducer from "./winnerSlice";
    
    const store = configureStore({
      reducer: {
        winners: winnersReducer,
        // ... other reducer functions
      }
    });
    
    ...