简体   繁体   中英

Not able to access response object via this.props | React/ Redux

When I try to access to the response object in my component it doesnt throw me an error but it wont either print. I do get access to the response in the component but thats it, i cant actually print something.

Actions File

 import axios from 'axios';
 import { FETCH_USERS, FETCH_USER } from './types';


const BASE_URL = "http://API_URL/endpoint/"
export function fetchUsers(id,first_name, last_name, dob) {
  const request = axios.post(`${BASE_URL}member-search?patientId=${id}&firstName=${first_name}&lastName=${last_name}&dateOfBirth=${dob}&length=10`).then(response => { return response; })

  return {
    type: FETCH_USERS,
    payload: request
  };
}

export function fetchUser(id) {
  const request = axios.get(`${BASE_URL}members/${id}/summary/demographics`).then(response => { return response; })

    return{
      type: FETCH_USER,
      payload: request
    };
}

My reducer file

import _ from 'lodash';
import {
  FETCH_USERS, FETCH_USER
} from '../actions/types';

export default function(state = [], action) {
  switch (action.type) {
    case FETCH_USER:
      return { ...state, [action.payload.data.member.id]: action.payload.data.member };
      // return [ action.payload.data.member, ...state ];
    case FETCH_USERS:
      return _.mapKeys(action.payload.data.searchResults, 'id');
  }

  return state;
}

And finally my component where Im trying to render some results of the response.

    import React, { Component } from 'react';
import { connect } from 'react-redux';
import { Link } from 'react-router-dom';
import { fetchUser } from '../actions';



class PatientWrapper extends Component{
  componentDidMount() {
    const { id } = this.props.match.params;
    this.props.fetchUser(id);

  }
  render(){
    const { user } = this.props;
    console.log('this.props response: ',user);

    if(!user){
      return <div>loading...</div>;
    }

    return(
      <div>
        Name: {user.firstName}
        Last Name: {user.lastName}
      </div>
    )
  }
}
function mapStateToProps({ users }, ownProps) {
  // return { users };
  return { user: users[ownProps.match.params.id] };
}
export default connect (mapStateToProps, { fetchUser })(PatientWrapper);

I uploaded a Screenshot img of the response : http://prntscr.com/fbs531

What is wrong with my code?

The issue is that in fetchUser action you use a Promise and return it in payload field. This promise does not contain any information you need like response data. So to fix the issue you need to dispatch action only when response is retrieved (eg in then success callback).

To implement it you need to pass mapDispatchToProps in the second argument in connect function for your component and pass dispatch function to your action:

function mapDispatchToProps(dispatch) {
    return {
        fetchUser: id => fetchUser(id, dispatch)
    }
}

Then in the action just do the following

function fetchUser(id, dispatch) {
    const request = axios.get(`${BASE_URL}/${id}`)
        .then(response => dispatch({
            type:FETCH_USER,
            payload: response
        }));
}

For complete example see JSFiddle

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM