Home > Back-end >  Update state of an array
Update state of an array

Time:12-06

When changing the state of an element from true to false coming from a checkbox, performing the setState does not update the screen -- it is necessary to press another element on the screen with state to later update the value of the checkbox.

let arrayNiveis = [
        {
            id: 1,
            codigo: 16,
            filhos: [
                {
                    id: 2,
                    codigo: 17,
                    filhos: null,
                    marcado: false,
                    menu: 1,
                    nivel: 1,
                    nome: "Listar",
                    opcao: 2,
                    pai: 1
                },
                {
                    id: 3,
                    codigo: 19,
                    filhos: null,
                    marcado: false,
                    menu: 1,
                    nivel: 2,
                    nome: "Disponível",
                    opcao: 2,
                    pai: 1
                }
            ],
            marcado: false,
            menu: 1,
            nivel: 0,
            nome: "MANUTENÇÃO DE SERIAIS",
            opcao: 2,
            pai: null
        }
    ];

const handleCheckBox = (e: any) => {
        let eleId = parseFloat(e.target.id);
        arrayGrupoNiveis.map((nivelItem: any) => (
            nivelItem.filhos.map((filho: any) => {
                if (filho.id == eleId) {
                    filho.marcado = !filho.marcado
                }
            })
        ))
        setArrayGrupoNiveis(arrayGrupoNiveis);
    };

When setting the state in setArrayGrupoNiveis, the screen is not updated with the same value.

CodePudding user response:

The reason you aren't getting an update is because setState uses Object.is() internally. This means that it is comparing the reference of the array in memory. By looping over arrayNiveis and mutating it, you aren't changing the reference to the array. So when you use setArrayGrupoNiveis(), React doesn't find a difference and hence the re-render isn't triggered.

What you should do is make a copy of this array and then use that in the setsetArrayGrupoNiveis() hook which would change the reference and hence trigger the re-render.

CodePudding user response:

Bro, what are you trying to do?! do you want to change values inside the array? are you sure this code is working

filho.marcado = !filho.marcado

another thing is you need to use return when you have nested maps, specially when you are using it as a function.

try to use return, it might work.

return filho.marcado = !filho.marcado
  • Related