Home > Enterprise >  How to set a state with object in array using loop in reactjs
How to set a state with object in array using loop in reactjs

Time:12-12

I'm facing a problem with setting a state with an object in an array using a loop in my project. when I loops the data only set of them.

this is my code

    const {role} = usePage().props
const { data, setData, put, processing, errors, reset } = useForm({
    name: role.name || '',
    permissions: []

})

const setUncheckPermissions = () => {
    const temp = props.permissions.map((permission) => {
        return permission['name']
    })

    if(props.permissions.length > role.permissions.length){
        for(let i=0; i < temp.length; i  ){
            setData("permissions", [{name:temp[i],isChecked:false}]); // only set one of them 
        }

        return console.log('all good')
    }

    return console.log('Maybe problems happen')

}

please give me some clue or hint or better terminology to solve this problem. thank you in advance

CodePudding user response:

setData("permissions", temp.map(it => ({name: it, isChecked: false})))

CodePudding user response:

You seem to be mapping to every permission object the property isChecked: false

For this you only need to work with your map function once and then set the state for the whole permissions.

No need to map once for taking the name property out and loop through it to set the isChecked property. All can be done in one go. Furthermore, calling setData in a loop will make your component re-render on every iteration, which is undesired.

Simply do this:

const setUncheckPermissions = () => {
    if(props.permissions.length > role.permissions.length){
        const uncheckedPermissions = props.permissions.map((permission) => {
            return {name: permission.name, isChecked: false};
        })
        setData("permissions", uncheckedPermissions);
    }
}
  • Related