Search code examples
reactjsreduxreact-reduxstorereducers

How to bring the response of an XHR request into state with React-Redux


I am trying to get the response of an XHR request as a prop in my React container. What I'm trying to do is make a GET request to an api, and turn the response into an object called "game" that I can access in react. I successfully did something similar with a GET request that returned an array of objects called "games" which I could map over in react; however, when I try the request for the "game" object, I get a good response from the api, but react shows "game" as undefined.

I think the problem I'm having might be with my reducer or action file, perhaps how I have my initial state set up, but I can't figure out how to get it to work.

Thank you for any and all help you can provide! I truly appreciate your time and patience.

I am posting my code below.

The reducer file looks like this:

import { LOAD_GAMES, SET_CURRENT_GAME } from "../actionTypes";

const game = (state = [], action) => {
    switch (action.type) {
        case LOAD_GAMES:
            return [...action.games];
        case SET_CURRENT_GAME:
            return [...action.game];
        default:
            return state;
    }
};

export default game;

The action files looks like this:

import { apiCall } from "../../services/api";
import { addError } from "./errors";
import { LOAD_GAMES, SET_CURRENT_GAME } from "../actionTypes"; 

export const loadGames = games => ({
  type: LOAD_GAMES,
  games
});

export const setCurrentGame = game => ({
    type: SET_CURRENT_GAME,
    game
});

export const fetchGames = () => {
  return dispatch => {
    return apiCall("GET", "api/games/")
      .then(res => {
        dispatch(loadGames(res));
      })
      .catch(err => {
        dispatch(addError(err.message));
      });
  };
};

//WRITE A FUNCTION TO SET_CURRENT_GAME TO BE THE ID OF THE GAME THAT IS CLICKED ON.
export const getGameDetails = game_id => {
    return dispatch => {
        return apiCall("GET", `/api/games/${game_id}`)
            .then(res => {
                dispatch(setCurrentGame(res));
        })
        .catch(err => {
            dispatch(addError(err.message));
        });
    };
};

export const postNewGame = title => (dispatch, getState) => {
  return apiCall("post", "/api/games", { title })
    .then(res => {})
    .catch(err => addError(err.message));
};

And the React container looks like this:

import React, { Component } from "react";
import { connect } from "react-redux";
import { Link } from "react-router-dom";
import { getGameDetails } from "../store/actions/games";

class GameDetails extends Component {

componentDidMount() {
    const game_id= this.props.match.params.game_id;
    this.props.getGameDetails(game_id);
}
render() {
    const { game } = this.props;

    return (
        <div className="home-hero">
            <div className="offset-1 col-sm-10">
                    <h4>You are viewing the Game Page for {game.title}</h4>
            </div>
        </div>
    );
}
}

function mapStateToProps(state) {
return {
    game: state.game
    };
}

export default connect(mapStateToProps, { getGameDetails })(
    GameDetails
);

EDIT -- The GameList container that is working by displaying the map of the games response array looks like this:

import React, { Component } from "react";
import { connect } from "react-redux";
import { Link } from "react-router-dom";
import { fetchGames } from "../store/actions/games";

class GameList extends Component {
    componentDidMount() {
        this.props.fetchGames();
    }
    render() {
        const { games } = this.props;
        let gameList = games.map(g => ( 
            <li className="list-group-item" key= {g._id}>
                <Link to={`/games/${g._id}`}>
                    {g.title}
                </Link>
            </li>
        ));
        return (
            <div className="row col-sm-8">
                <div className="offset-1 col-sm-10">
                    <ul className="list-group" id="games">
                        {gameList}
                    </ul>
                </div>
            </div>
        );
    }
}

function mapStateToProps(state) {
    return {
        games: state.games
    };
}

export default connect(mapStateToProps, { fetchGames })(
    GameList
);

For clarification, the "LOAD_GAMES" part of the reducer and actions works well; however, the "SET_CURRENT_GAME" isn't working.


Solution

  • I think you are using reducer wrong

    State of reducer should be object, not array IMO, for example like this:

    import { LOAD_GAMES, SET_CURRENT_GAME } from "../actionTypes";
    
    const initState = {
        current: {},
        list: []
    }
    const game = (state = initState, action) => {
        switch (action.type) {
            case LOAD_GAMES:
                return {
                                ...state,
                                list: action.games
                            };
            case SET_CURRENT_GAME:
                return {
                                ...state,
                                current: action.game
                            };
            default:
                return state;
        }
    };
    
    export default game;
    

    Than in GameDetails

    function mapStateToProps(state) {
        return {
           game: state.games.current
        };
    }
    

    And in same GameList

    function mapStateToProps(state) {
        return {
           list: state.games.list
        };
    }