1

I have a piece of code wherein I am trying to change the state of an array of objects (I want to clear it out) when certain conditions are met. The conditions I have written are correct but I am unable to change the state of the array using the setState hook. I'll add the code snippets below and try to explain further

This is how we are initialising the state variable 'arrayOfObjects'.

const [arrayOfObjects, setArrayOfObjects] = useState(
        objects.map(object => ({
            id: `${object.type}`,
            value: false,
            text: object.name,
            privilege: object.privilege,
            disabled: false
        }))
    );

Later on in the code I am checking certain conditions and trying to empty out the arrayOfObjects state variable as below

setArrayOfObjects([])

This doesn't give me an error but it also doesn't work. The objects array always has data in it. Could anyone tell me what I am doing wrong?

I also tried

setArrayOfObjects(arrayOfObjects.filter(arrayOfObjects => arrayOfObjects.privilege !== 12345678));

but that didn't work as well.

I also tried the following but I am fairly new to React and don't know if I am doing this correctly. This also didn't work

useEffect(() => {
setArrayOfObjects([])
}, [arrayOfObjects])

I also tried to create a type for the arrayOfObjects array and used that where the state variables are initialised but got an error

interface ITestInterface extends IListOption {
    privilege: number | null;
}

The IListOption is as follows

export interface IListOption {
    id: string;
    text: string;
    value: boolean;
    disabled?: boolean;
}

Used as below

const [arrayOfObjects, setArrayOfObjects] = useState<IPrivilegeListOption | undefined>(
        objects.map(object => ({
            id: `${object.type}`,
            value: false,
            text: object.name,
            privilege: object.privilege,
            disabled: false
        }))
    );

The error I get is

Argument of type '{ id: string; value: boolean; text: string; privilege: number | null; disabled: boolean; }[]' is not assignable to parameter of type 'ITestInterface | (() => ITestInterface | undefined) | undefined'.

I am not sure what else I could try

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.