What is recommended way to determine if a Redux state empty array is the initial state or the result of an API call that returns an empty array?

Viewed 661

Let say I have an initial state tree that looks like this:

    {
      users: [],
      items: []
    }

In some cases, the result of calling the items API endpoint may result in a state tree like this:

    {
      users: [],
      items: [
              {itemId: 100, itemName: "Something100"},
              {itemId: 101, itemName: "Something101"}
             ]
    }

In other cases where there are not items to display, the state tree after an API call will be identical to the initial state tree.

Now in my component I'm using useEffect, something like this:

  useEffect(() => {
      if (items.length === 0) {
        actions.loadItems().catch((error) => {
          alert("Loading items failed! " + error);
          console.log(error);
        });
      }
  }, [items , actions]);

In this particular case, the length of items will be 0 in two cases: initial state or in case there are no results. If the API returns zero items and items.length === 0, then the action to call the API is executed repeatedly.

We really need a way of knowing that the empty array is the initial state or not. Of course I could change the state tree to something like:

    {
      users: {isLoaded: false, records: []},
      items: {isLoaded: false, records: []},
    }

That is going to add a bunch of overhead and refactoring and may not be most efficient/effective, so can someone give me a recommendation?

1 Answers

Unfortunately you will need some way of tracking the initialisation. If the issue is having to refactor then you can pull out this initialisation state into a higher order in the object from what you suggested. This will avoid refactoring so much:

{
  isUsersLoaded: false,
  isItemsLoaded: false,
  users: [],
  items: []
}

Another alternative is to init like this and check if users !== null etc.:

{
  users: null,
  items: null
}
Related