How can I change the state of an array item in React Native

Asked

Viewed 2,549 times

1

I have a list that is loads after the return of the api, this list populates a Flatlist. By clicking on any item I would like to mark it with the status that was viewed: user

How can I change only the clicked item.

[
  {
    "id": 3,
    "codigoCondominio": "1212",
    "dataVencimento": "2018-03-10T00:00:00",
    "descricao": "Pagamento de taxa de licenciamento",
    "valor": 23900.9,
    "flagBloqueio": false,
    "dataBloqueio": null,
    "idUsuarioConcordou": null,
    "createTime": "2018-03-23T01:35:29.957",
    "arquivado": false,
    "dataPagamento": null,
    "numeroLancamento": 0,
    "codigo": "1212",
    "nome": "Edificio 0001",
    "usuarioViu": null,
    "flagVisualizado": null,
    "vencido": true
  },
  {
    "id": 4,
    "codigoCondominio": "1212",
    "dataVencimento": "2018-03-10T00:00:00",
    "descricao": "Pacto administradora",
    "valor": 45000,
    "flagBloqueio": true,
    "dataBloqueio": null,
    "idUsuarioConcordou": null,
    "createTime": "2018-03-23T01:36:06.52",
    "arquivado": false,
    "dataPagamento": null,
    "numeroLancamento": 0,
    "codigo": "1212",
    "nome": "Edificio 0002",
    "usuarioViu": null,
    "flagVisualizado": null,
    "vencido": true
  }
]

Simplifying I would like to change the first object [0]. userViu = true

I’m working with React-Native, Redux-saga

1 answer

2


You have to use TouchableHighlight so that items respond appropriately to touches.

  1. Set a method to update the property value.

    handleUsuarioViu = (index) => {
      let dados = this.state.dados;
      alert(dados[index].usuarioViu); // Apenas para demonstrar
      dados[index].usuarioViu = true;
      this.setState({ dados: dados });
    };
    

    The alert is only to demonstrate the functioning, at each touch/click, will display the current value. Then the property value is updated usuarioViu of the item that received the touch/click.

  2. On the estate renderItem of FlatList change to:

    <TouchableHighlight onPress={() => this.handleUsuarioViu(index)}>
      <Text>{item.nome}</Text>
    </TouchableHighlight>
    

You can see running on snack.expoio.

  • Thanks a lot, solved my problem.

Browser other questions tagged

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