How to extract data from Axios get request?

Viewed 202

I have two files. One is "actions.js" and the other one is "Profile.js". The first file has a function that calls an API that will get information about an user based on his/her id.

The code for "actions.js" is:

import axios from "axios";
export const getPerson = (id, history) => async dispatch => {
  try {
    const res = await axios.get(`http://localhost:6969/users/getUsers/${id}`);
    const { email } = res.data;
    console.log(email);
    dispatch({
      type: GET_PERSON,
      payload: res.data,

    });
  } catch (error) {
    history.push("/profile");
  }
};

The code for my "Profile.js" page is:

import React, { Component } from 'react'
import { getPerson } from '../actions/personActions';
import * as PropTypes from 'prop-types'
import { connect } from "react-redux";

render() {
        


  
        this.props.getPerson(id, this.props.history);

        ----------- Followed by render method
}

Profile.propTypes = {
    getPerson: PropTypes.func.isRequired
  };
  
const mapStateToProps = state => ({
errors: state.errors
});
  
export default connect(
    mapStateToProps,
    { getPerson }
)(Profile);

Problem is that I cannot show those responses in my Profile page by even localstorage if I decide to put the respective value in it. Tried with variety of ways but it shows up in the action.js page if I see from console using inspect log however it shows undefined in the Profile.js page. Please tell me where did I made it wrong. Thanks.

1 Answers

So, I think you're issue is that you're not dispatching anything in catch here:

} catch (error) {
  dispatch({
    // or something like this
    type: GET_PERSON,
    payload: error,

  });
  history.push("/profile");
}

Because of this, state is not updated with new error and state.errors is probably null or undefined. Also, If you're trying to render anything other than the error from the state, don't forget to add it to mapStateToProps.

Other than that, I would recommend against calling api function in render. That's a really bad idea, that's because you might get a lot of useless api calls or even a loop of renders. Either call it in componentDidMount or use useEffect hook.

Generally I would advise that you go through couple of more react/redux tutorials.

Related