Home > Blockchain >  Typescript error - Assignment to property of function parameter 'state' in ReduxJS Toolkit
Typescript error - Assignment to property of function parameter 'state' in ReduxJS Toolkit

Time:11-15

This is my code -

type LoginState = {
  loading: 'idle' | 'pending' | 'succeeded' | 'failed';
  role: string;
  error: string;
};

const initialState: LoginState = {
  loading: 'idle',
  role: '',
  error: '',
};

const userSlice = createSlice({
  name: 'user',
  initialState,
  reducers: {},
  extraReducers: builder => {
    builder
      .addCase(authUser.pending, (state: LoginState) => {
        state.loading = 'pending';
      })
      .addCase(authUser.rejected, (state, action) => {
        state.loading = 'failed';
        console.log('action', action);
      });
  },
});

And I am getting this error on TS -

enter image description here

I am not really sure, how I can resolve this. I have already added interfaces but seems I am missing something.

Can you guys help.

CodePudding user response:

This is caused by a linting rule you have setup/configured in your project. You can either completely disable the rule (not recommended), or override the rule in the few places where it makes sense, like here in the reducer function where you are directly setting properties on the state object. Add a comment that disables the specific rule for the next line of code.

Example:

const userSlice = createSlice({
  name: 'user',
  initialState,
  reducers: {},
  extraReducers: builder => {
    builder
      .addCase(authUser.pending, (state: LoginState) => {
        // eslint-disable-next-line no-param-reassign
        state.loading = 'pending';
      })
      .addCase(authUser.rejected, (state, action) => {
        // eslint-disable-next-line no-param-reassign
        state.loading = 'failed';
      });
  },
});

CodePudding user response:

need to sigtly disable this rule in .eslintrc to support assignment in the state

'no-param-reassign': ['error', {
  props: true,
  ignorePropertyModificationsFor: [
    'state',
  ]
}],

CodePudding user response:

Dont declare the type of the state. The own library should type it correctly as WritableDraft<LoginState> (It uses the provided type at initialState):

      .addCase(authUser.pending, (state) => {
        state.loading = 'pending';
      })
  • Related