user12541823
user12541823

Reputation:

different ways to define initialState for Redux Store

I recently came across this example:

state.d.ts

export interface IState {
    token: string | null;
  }

export const tokenReducer = (
  state: IState['token'] = null,
  { type, payload }: AppAction,
): typeof state => {
  switch (type) {
    case 'LOGIN':
      return payload;
    default:
      return state;
  }
};

This works well. However, I tried to change it like this:

const initialState: IState = {
  token: null
};

export const tokenReducer = (
  //state: IState['token'] = null,
  state = initialState,
  //state: initialState
  action: AppAction,
): typeof state => {
  switch (type) {
    case 'LOGIN':
      return action.payload;
    default:
      return state;
  }
};

but I get errors. Error on action.payload if I use state: typeof initialState or state = initialStateas per IDE's suggestion:

Type 'string' is not assignable to type 'IState'.ts(2322)

If I try state: initialStatethen obviously:

'initialState' refers to a value, but is being used as a type here. Did you mean 'typeof initialState'?ts(2749)
``
What am I doing wrong? Am I making a syntax error or is it just not allowed to define initialStates like this?

Upvotes: 0

Views: 86

Answers (1)

bbortt
bbortt

Reputation: 405

The problem probably is this: You're not returning the state at all. You're just overriding it or returning the token only (not as object), depending on your payload. I suppose that LOGIN-action will return a token. So the correct reducer would be as following:

export const tokenReducer = (
  state: IState['token'] = initialState,
  { type, payload }: AppAction,
): IState => {
  switch (type) {
      case 'LOGIN':
        return {
          ...state,
          token: payload,
        };
      default:
        return state;
    }
};

Or does payload contain {token: string}?

Edit: Aight, after looking carefully at the very first tokenReducer I think it reduces the token only, not an object. So a correct initialState would be:

// this equals the `token` in `IState`
const initialState: string | null = null

And yes, assigning state = initialState, is syntactically correct.

Upvotes: 2

Related Questions