createEntityAdapter with Typescript and React - the shape of initialState

19 Views Asked by At

While writing this message I have found the solution) Due to the time that I spent on searches, I want to leave it here in case someone had the same issue.

store.ts file

import team from './TeamSlice';

const store = configureStore({
  reducer: { team },
  devTools: process.env.NODE_ENV !== 'production',
});

export type RootState = ReturnType<typeof store.getState>;
export type AppDispatch = typeof store.dispatch;

export default store;

TeamSlice.ts file

export type Pokemon = { id: number; name: string; sprites: {} };

type InitialState = {
  team: Pokemon[];
};

const pokemonsTeamAdapter = createEntityAdapter();

const initialState: InitialState = pokemonsTeamAdapter.getInitialState({
  team: [],
});

const pokemonsTeamSlice = createSlice({
  name: 'team',
  initialState,
  reducers: {
    pokemonAdded: (state, action) => {
      pokemonsTeamAdapter.addOne(state, action.payload);
    },
    pokemonUpdated: pokemonsTeamAdapter.updateOne,
   // some other reducers
  },
});

export const { selectAll } = pokemonsTeamAdapter.getSelectors((state: RootState) => state.team);

No matter how reducer is set I received an error:

Argument of type 'WritableDraft' is not assignable to parameter of type 'DraftableEntityState<{ id: EntityId; }, EntityId>'

The only thing I had to do was rewrite InitialState type as below:

export type Pokemon = { id: number; name: string; sprites: {} };

type Team = {
  team: Pokemon[]
}

type InitialState = DraftableEntityState<{id: EntityId}, EntityId> & Team;

I expect that it will save time for someone and I will find out better approaches.

0

There are 0 best solutions below