0

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

2 Answers 2

1
setData("permissions", temp.map(it => ({name: it, isChecked: false})))
Sign up to request clarification or add additional context in comments.

1 Comment

i see , i need to loop inside , thx brother
1

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);
    }
}

1 Comment

thx for the advice brother , this way also looks cool

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.