Retrieving last record from JSON is not showing anything

I have an API that returns an array, where I need to get the last generated record to show in react native:

{
    "faturas": [
        {
            "vencimento_atualizado": "2020-10-05",
            "status": "Pago",
            "pagarcartao": false,
            "id": 20075
        },
        {
            "vencimento_atualizado": "2020-11-05",
            "status": "Gerado",
            "pagarcartao": false,
            "id": 20076
        },
        {
            "vencimento_atualizado": "2020-12-05",
            "status": "Gerado",
            "pagarcartao": false,
            "id": 20077
        }
    ]
}

The last one is greater than the “id”, and filter only the “Paid” and “Generated” statuses?

My code:

return await fetch(Configs.URL+`json/data_faturas.php?cpfcnpj=${cpfcnpj}&senha=${senha}&contrato=${this.state.contrato}&ip=${Configs.IP}`)
      .then((response) => response.json())
      .then((responseJson) => {
        this.setState({
          isLoading: false,
          dataInvoice: responseJson.filter((e, index) => { return index < 2 })
        });
      }).catch((error) => {
        console.log('ERRO: '+error);
      }).done();

Thanks

Hi @edilsonlsouza

This question is not about Expo. It’s not even about React Native or React. It’s really about JavaScript or the JavaScript filter array method.

So this is not the right place to ask the question.

But also, I don’t understand what you’re asking.

You say your code is not showing the last record, but the code is specifically asking for only the first two entries in the array:

If you want all of them then remove the filter() call.

Also, this part seems to be a different question altogether:

What “id” are you referring to as the last one being greater than?

If you only want the ones where status is “Paid” or “Generated”, then do something like this:

    this.setState({
      isLoading: false,
      dataInvoice: responseJson.filter((e) => {
        return e.status === "Paid" || e.status === "Generated";
      }),
    });

One other thing. Instead of interpolating those query parameters one by one into the string in the fetch() call, you can do it like this:

  const params = new URLSearchParams({
    cpfcnpj: cpfcnpj,
    senha: senha,
    contrato: this.state.contrato,
    ip: Configs.IP,
  });
  return await fetch(`${Configs.URL}json/data_faturas.php?${params.toString()}`)
    .then((response) => response.json())
// [...]
1 Like

Hi

As @wodin said, this is more of a Javascript issue than an Expo or React Native one.

If you want to obtain the item with the highest ID, you can use the Array.reduce, something like this:

let latestItem = responseJson.reduce((prev, current) => return (prev.id > current.id) ? prev : current)
2 Likes

This topic was automatically closed 20 days after the last reply. New replies are no longer allowed.