Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Getting error on updating boolean state in Redux

My state data:

options: [
      {
        id: 1,
        name: "Sale",
        isTrue: false,
      },
      {
        id: 2,
        name: "New in",
        isTrue: false,
      },
    ],

And, in reducers I have:

    closeOptions: (state) => {
      state.options  = state.options.map((item) => (item.isTrue = false));
    },

But I am getting error in state.options with red underline in vscode. And, it shows below error:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Type 'boolean[]' is not assignable to type 'WritableDraft<{ id: number; name: string; isTrue: boolean; }>[]'.
  Type 'boolean' is not assignable to type 'WritableDraft<{ id: number; name: string; isTrue: boolean; }>'.ts(2322)

More,

  Unhandled Runtime Error
TypeError: Cannot create property 'isTrue' on boolean 'false'

Source

  105 | closeOptions: (state) => {
> 106 |   state.options = state.options.map((item) => (item.isTrue = false));
      |                                                          ^
  107 | },

How can I resolve this issue?

Whole project in TS

>Solution :

You’re getting these errors:

Type 'boolean[]' is not assignable to type 'WritableDraft<{ id: number; name: string; isTrue: boolean; }>[]'.
Type 'boolean' is not assignable to type 'WritableDraft<{ id: number; name: string; isTrue: boolean; }>'.ts(2322)

Because when you use state.options.map((item) => (item.isTrue = false)) in closeOptions it’s returning [false, false] whose type is boolean[] which is completely different from type WritableDraft<{ id: number; name: string; isTrue: boolean; }>[].

Change closeOptions function to this:

closeOptions: (state) => {
   state.options?.forEach((item) => (item.isTrue = false))
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading