M
M
mDrama2020-05-11 14:23:36
React
mDrama, 2020-05-11 14:23:36

Redux - API request completion rate?

Good afternoon. Already asked this question on another resource, but no one answered there. I'll try my luck here.

The question concerns the implementation of the execution status of an asynchronous request, thanks to which the component will understand when the data has loaded and can be used when rendering (saga / thunk - it doesn’t matter).

For example, I fetch a list of some items from the server, then in the parent component I create a list of cards for each item using .map(). I need the component to understand when the data has arrived and it can start using it for rendering.

All the tutorials say that the reducer needs the loading, isLoading property (and so on):

const INITIAL_STATE = {
  allGamesCollection: null,
  loading: false,
  error: null
}


Here I have this loading property. By default, it should again be false. For the api request, we create 3 actions of the type fetchAllGamesStart, fetchAllGamesSuccess, fetchAllGamesFailure. And in them we change the value of loading.

case AllGamesActionTypes.FETCH_ALLGAMES_START:
      return {
        ...state,
        loading: true
      }
    case AllGamesActionTypes.FETCH_ALLGAMES_SUCCESS:
      return {
        ...state,
        allGamesCollection: action.payload,
        loading: false,
        error: null
      }
    case AllGamesActionTypes.FETCH_ALLGAMES_FAILURE:
      return {
        ...state,
        error: action.payload,
        loading: false,
        allGamesCollection: null
      }


Then we take this property with a selector and import it into the component, in which then there will be something like this:

{
     loading ? <Spinner /> : allGames.map(game => <GamePreviewItem game={game} key={game.id} />)
}


Spinner is just a mini component with a spinning loading animation. Instead, you can simply enter null.

My problem is that if the default value of the reducer is false, then the component immediately throws an error, because it tries to map the data when it has not yet arrived. This happens because (as far as I understand) it initially takes loading from the reducer with its default value (false). In the reducer, you can give it the default value true and everything will work fine. But this is illogical. Yes, and everywhere on all sites such properties have a false value and I don’t understand how it works for them and why it doesn’t work for me.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry Sviridov, 2020-05-11
@mDrama

What if it's like this?

const INITIAL_STATE = {
  allGamesCollection: [],
  loading: false,
  error: null
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question