Hooks: Usestate with dynamic array manipulation in React Native

Asked

Viewed 191 times

0

Good morning/afternoon/evening, I need your help if possible...

I own a hook

const [itens, setItens] = React.useState([
    {
      id: 1,
      nome: "Item 1"
    },
    {
      id: 2,
      nome: "Item 2"
    }
  ]);

In fact it is blank, and was fed via API, being filled with JSON above. Now, on the screen, I have 2 inputs that were generated through a MAP of this Hook, however, to be able to change the item with the input, receiving the information of an ARRAY that is in Hook form, I had to work with the Index beyond the Value, with the code being like this:

//Função para atualizar uma única linha do Hook 
const atualizaItem = (index, value) => {
    let rows = itens;
    rows[index].nome = value;
    setItens(rows);
};

//Função que o MAP do hook vai retornar
const oItem = (row, index) => (
  <Input key={row.id} value={itens[index].nome} onChangeText={value => atualizaItem(index, value)} />
);

//MAP do Hook
{itens.map((row, index) => oItem(row, index))}

Explaining a little the concept of the code, I have a HOOK with an Array, having several lines, and for each line I have an INPUT that, when changing the content of it, the HOOK will also be changed, its respective field, within its respective line.

This was supposed to work in theory (I think), the problem is that, if I use the console.log in the update functionItem, it shows me that Hook has been updated, but the screen has not been rendered, so inside the Input the value remains fixed, always the same.

This code below works perfectly, if I change the input, it changes the hook normally.

const [nome, setNome] = React.useState('');
<Input placeholder="Nome" value={nome} onChangeText={value => setNome(value)} />

That is, if it is a simple text hook, it works perfectly, but if it is an Array, besides I have to generate an input for each item (within my need, I need an Input for each one), I also need to know which exactly I am changing, save and obviously show on screen.

And for starters, I’m not sure if the way I’m doing this is the best possible way.

Could someone help me?

Thank you very much.

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.