2

Im trying to make an api request from redux then take that data and put it in my react state (arrdata). The api call works but i cant seem to get the state on my app.js to update based on the redux api call. Am i missing something?

App.js

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      arrdata: []
    };
  }
  componentDidMount() {
    this.props.loadData();
    console.log(this.props.data);
  }
  render() {
     const {arrdata} = this.state
    return ( ......)}}


const mapStateToProps = state => {
  return {
    data: state.data
  };
};

export default connect(mapStateToProps, dataAction)(App);

Action

export function loadData() {
  return dispatch => {
    return axios.get("https://api.coincap.io/v2/assets").then(response => {
      dispatch(getData(response.data.data.slice(0, 10)));
    });
  };
}

export function getData(data) {
  return {
    type: "GET_DATA",
    data: data
  };
}

Reducer

let initialState = {
  data: []
};

const mainReducer = (state = initialState, action) => {
  if (action.type === "GET_DATA") {
    return {
      ...state,
      data: action.data
    };
  } else {
    return {
      ...state
    };
  }
};

export default mainReducer;
Community
  • 1
  • 1
Ahmed Ali
  • 105
  • 2
  • 10
  • Possible duplicate of [Understanding React-Redux and mapStateToProps()](https://stackoverflow.com/questions/38202572/understanding-react-redux-and-mapstatetoprops) – Emile Bergeron Nov 22 '19 at 18:15

1 Answers1

2

I think you are misleading store with state. Your arrdata is empty since it's stored inside state, but your data comes from props.

Anyways, arrdata in state remains empty, since you are not setting the state anywhere. To do that, you would have to use e.g. getDerivedStateFromProps lifecycle hook, however I wouldn't recommend that.

render() {
   const { data } = this.props;
   console.log(this.props.data);

   return (
     // do something with your data
   );
}

It should log your data properly.

Note: You don't need state, actually. It's a better approach to manipulate over props, instead of saving data from props into state (in most cases).

kind user
  • 40,029
  • 7
  • 67
  • 77