score:1

Accepted answer

Dispatch a single action to update the store for result instead of dispatching multiple actions per field in the result.

src/actions/index.js


export const RECEIVE_TEAMS_STATS = "RECEIVE_TEAMS_STATS";


export const receivedTeamsStat = json => ({
  type: RECEIVE_TEAMS_STATS,
  json: json
});

export function getTeamsStats(league, team) {
  return function(dispatch) {
    return axios
      .get(
        `https://www.api-football.com/demo/api/v2/statistics/${league}/${team}`
      )
      .then(res => {
        const { 
          wins: { home: teamsStatsWinHome, away: teamsStatsWinAway }, 
          draws: { home: teamsStatsDrawHome, away: teamsStatsDrawAway }, 
          loses: { home: teamsStatsLoseHome, away: teamsStatsLoseAway }
        } = res.data.api.statistics.matchs;
        const teamStats = {
          teamsStatsWinHome,
          teamsStatsWinAway,
          teamsStatsDrawHome,
          teamsStatsDrawAway,
          teamsStatsLoseHome,
          teamsStatsLoseAway
         }
        dispatch(receivedTeamsStat(teamStats));
      })
      .catch(e => {
        console.log(e);
      });
  };

All 6 actions (RECEIVE_TEAMS_STATS_WIN_HOME, RECEIVE_TEAMS_STATS_WIN_AWAY, RECEIVE_TEAMS_STATS_DRAW_HOME, RECEIVE_TEAMS_STATS_DRAW_AWAY, RECEIVE_TEAMS_STATS_LOSE_HOME, RECEIVE_TEAMS_STATS_LOSE_AWAY) can be rolled into a RECEIVE_TEAMS_STATS action and handled as follows:

src/reducers/index.js

import {
  //..
  RECEIVE_TEAMS_STATS
} from "../actions";


const reducer = (state = initialState, action) => {
  switch (action.type) {
    //...
    case RECEIVE_TEAMS_STATS:
      return {
        ...state,
        ...action.json,
        isTeamsStatsLoading: false
      };
    //...
}

The benefit of dispatching a single update to the store is that Stats component renders once as opposed to 6 times when results return from the API.


Related Query

More Query from same tag