How to manipulate an empty filter?

Asked

Viewed 69 times

1

I need a logic that displays a <Text> saying that there are no items when the produtosArr.filter() is empty (or when the filter does not return anything to me).

      <List.Subheader>Vencimento próximo</List.Subheader>
        {this.state.produtosArr.filter(r => {
          const diff = dateDiffInDays(Date.parse(r.data_vencimento.replace(/-/g, "/")), Date.now());
          if (diff >= -7 && diff < 0) {
            return true;
          }
          return false;
        }).map(r => <>
          <List.Item
            title={r.nome_produto}
            description={"Vencimento em " + dateDiffInDays(Date.now(), Date.parse(r.data_vencimento.replace(/-/g, "/"))) + " dias"}
            left={props => <List.Icon {...props} icon="box" />}
          />
        </>)}

When the this.state.produtosArr.filter does not return anything, simply the list is empty, and do not want it, I want to show a message saying that there are no items in this list.

How do I do that?

1 answer

3


You should already know this, but when the filtering function passed to filter returns false, the iteration element in question is simply removed from the list. Thus, if none of the items passes the filtering criterion, the final array will be empty - since all items have been removed.

This way, you can simply filter out the return of the function that renders the component, so you can evaluate whether the list length is greater than zero.

Something like that:

class MyComponent extends React.Component {
  render() {
    const filtered = this.state.produtosArr.filter((r) => {
      // Sua lógica de filtro.
    });

    if (!filtered.length) {
      return <Text>Não há itens.</Text>;
    }

    return (
      <>
        {filtered.map((r) => {
          // Renderizar cada item normalmente.
        })}
      </>
    );
  }
}

Browser other questions tagged

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