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

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 (e.g. 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

Related

Axios request sent twice when using React Saga

I am trying to send a GET request using axios and React Saga.
The request fired twice
This is my component file where I call the getBusinessHoursList action:
import { getBusinessHoursList } from "../../../../redux/actions";
...
...
componentDidMount() {
this.props.getBusinessHoursList(this.state.id);
}
...
...
const mapStateToProps = ({ settings }) => {
return {
settings
};
};
export default connect(
mapStateToProps,
{
getBusinessHoursList,
}
)(injectIntl(BusinessHours));
This is my service file where I use axios to get my business hours list:
setting-service.js:
import axios from '../util/api';
import { configureStore } from '../redux/store';
export const settingsService =
{
getBusinessHours,
};
function getBusinessHours() {
const store = configureStore({});
const user = JSON.parse(store.getState().authUser.user)
return axios.get("business/" + user.business.id + "/businesshours")
.then(response => {
return response.data.data
}).catch(error => {
return error.response.data
})
}
This is actions file where I define the actions
actions.js:
import {
CHANGE_LOCALE,
SETTING_GET_BUSINESS_HOURS_FAIL,
SETTING_GET_BUSINESS_HOURS_SUCCESS,
SETTING_GET_BUSINESS_HOURS,
} from '../actions';
export const getBusinessHoursList = (data) => ({
type: SETTING_GET_BUSINESS_HOURS,
payload: data
});
export const getBusinessHoursSuccess = (items) => ({
type: SETTING_GET_BUSINESS_HOURS_SUCCESS,
payload: items
});
export const getBusinessHoursFail = (error) => ({
type: SETTING_GET_BUSINESS_HOURS_FAIL,
payload: error
});
reducer.js
import {
CHANGE_LOCALE,
SETTING_GET_BUSINESS_HOURS,
SETTING_GET_BUSINESS_HOURS_FAIL,
SETTING_GET_BUSINESS_HOURS_SUCCESS
} from '../actions';
const INIT_STATE = {
errors: '',
loadingBH: false,
businessHoursItems: null
};
export default (state = INIT_STATE, action) => {
switch (action.type) {
case SETTING_GET_BUSINESS_HOURS:
return { ...state, loadingBH: false };
case SETTING_GET_BUSINESS_HOURS_SUCCESS:
return { ...state, loadingBH: true, businessHoursItems: action.payload};
case SETTING_GET_BUSINESS_HOURS_FAIL:
return { ...state, loadingBH: true, errors: action.payload };
default: return { ...state };
}
}
saga.js:
import { all, call, fork, put, takeEvery, takeLatest, take } from "redux-saga/effects";
import { getDateWithFormat } from "../../helpers/Utils";
import { settingsService } from '../../services/settings-service'
import {
SETTING_GET_BUSINESS_HOURS,
SETTING_UPDATE_BUSINESS_HOURS,
} from "../actions";
import axios from "../../util/api";
import { NotificationManager } from "../../components/common/react-notifications";
import {
getBusinessHoursSuccess,
getBusinessHoursFail,
} from "./actions";
const getServiceListRequest = async () =>
await settingsService.getBusinessHours()
.then(authUser => authUser)
.catch(error => error);
function* getBusinessHours() {
console.log('test')
try {
const response = yield call(getServiceListRequest);
yield put(getBusinessHoursSuccess(response));
} catch (error) {
yield put(getBusinessHoursFail(error));
}
}
export function* watchGetBusinessHours() {
yield takeLatest(SETTING_GET_BUSINESS_HOURS, getBusinessHours);
}
export default function* rootSaga() {
yield all([
fork(watchGetBusinessHours),
]);
}
Global sagas file : sagas.js:
import { all } from 'redux-saga/effects';
import authSagas from './auth/saga';
import settingsSagas from './settings/saga';
export default function* rootSaga(getState) {
yield all([
authSagas(),
settingsSagas(),
]);
}
The request fired successfully and I get Business hours list but the request fired twice
I tried to use takeLatest in place of takeEvery
This is the network tab

React Redux action object is undefined

I am new to React-Redux and I have a problem with redux action object. When I am printing the object to the console, it displays correctly as shown below:
Please check my codes.
FeedPage.jsx
class FeedPage extends React.Component {
componentDidMount() {
const { id } = this.props.match.params;
this.props.dispatch(feedActions.getById(id));
console.log("props", this.props);
}
render() {
const { user, feed } = this.props;
...
function mapStateToProps(state) {
const { feed, authentication } = state;
const { user } = authentication;
console.log(JSON.stringify(feed));
return {
user,
feed
};
}
const connectedFeedPage = connect(mapStateToProps)(FeedPage);
export { connectedFeedPage as FeedPage };
reducer.js
export function feeds(state = {}, action) {
switch (action.type) {
case feedConstants.GETBYID_REQUEST:
return {
loading: true
};
case feedConstants.GETBYID_SUCCESS:
console.log("GETBYID_SUCCESS: " + JSON.stringify(action.feed));
return {
feed: action.feed
};
case feedConstants.GETBYID_FAILURE:
return {
error: action.error
};
...
service.js
function getById(id) {
const requestOptions = {
method: 'GET',
headers: authHeader()
};
return fetch(`${config.apiUrl}/feed/${id}`, requestOptions).then(handleResponse);
}
actions.js
function getById(id) {
return dispatch => {
dispatch(request());
feedService.getById(id)
.then(
feed => dispatch(success(feed)),
error => dispatch(failure(error.toString()))
);
};
function request() { return { type: feedConstants.GETBYID_REQUEST } }
function success(feed) { return { type: feedConstants.GETBYID_SUCCESS, feed } }
function failure(error) { return { type: feedConstants.GETBYID_FAILURE, error } }
}
UPDATE:
root reducer
import { combineReducers } from 'redux';
import { authentication } from './authentication.reducer';
import { registration } from './registration.reducer';
import { users } from './users.reducer';
import { alert } from './alert.reducer';
import { feeds } from './feeds.reducer';
const rootReducer = combineReducers({
authentication,
registration,
users,
alert,
feeds
});
export default rootReducer;
This is the screenshot of the logs:
So it is clear that feed object is not empty. But when I am referencing it, it is undefined. Please help as I am stuck and cannot move forward. Any help is great appreciated. Thank you!
In your root reducer, you are saying that the item "feeds" will contain what your feedReducer gives it. In your feedReducer you return "feed: action.feed".
So, in your mapStateToProps, you should be mapping "feeds", not "feed". When you then read the feeds value, it will contain an object such as { feed: xxx } where xxx is what your action originally had in it after your API call.
There's an issue with your reducer. You're mutating component state as it store doesn't get updated when we mutate the state and component doesn't re render
case feedConstants.GETBYID_SUCCESS:
console.log("GETBYID_SUCCESS: " + JSON.stringify(action.feed));
return {
...state,
feed: action.feed
};
in your case Redux doesn't detect a difference in state and won't notify your components that the store has changed and you should return a new copy of state with the necessary change. Hope this would solve the issue
Let me know if the issue still persists.

Cannot access data request Axios, React-Redux

I am trying to make an API request using Axios in React-Redux environment. On the console everything seems to be fine, however if I try to access any of the data I either get undefined or empty array.
This is my component:
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { discoverMovie } from '../actions'
//Home component
class Home extends Component {
//make request before the render method is invoked
componentWillMount(){
this.props.discoverMovie();
}
//render
render() {
console.log('movie res ',this.props.movies.movies.res);
console.log('movie ',this.props.movies);
return (
<div>
Home
movie
</div>
)
}
};
const mapStateToProps = (state) => {
return{
movies : state.movies
}
}
export default connect(mapStateToProps, { discoverMovie })(Home);
This is my action
import { DISCOVER_MOVIE } from '../constants';
import axios from 'axios';
//fetch movie
const fetchMovie = () => {
const url = 'https://api.themoviedb.org/3/discover/movie?year=2018&primary_release_year=2018&page=1&include_video=false&include_adult=false&sort_by=vote_average.desc&language=en-US&api_key=72049b7019c79f226fad8eec6e1ee889';
let result = {
res : [],
status : ''
};
//make a get request to get the movies
axios.get(url).
then((res) => {
result.res = res.data.results;
result.status = res.status;
return result;
});
//return the result after the request
return result;
}
//main action
const discoverMovie = () =>{
const result = fetchMovie();
//return the action
return {
type : DISCOVER_MOVIE,
payload : result
}
}
export default discoverMovie;
This is the reducer
import { DISCOVER_MOVIE } from '../constants';
//initial state
const initialState = {
movies : {},
query : '',
};
//export module
export default (state = initialState, actions) =>{
switch(actions.type){
case DISCOVER_MOVIE :
return {
...state,
movies : actions.payload
};
default :
return state;
}
}
this is the log that I get from the console
as you can see if I log the entire object I see all data, however if go deep and try to access the result I either get an undefined or an empty array and using redux-dev-tools I noticed that the state does not contain any value.
I read on internet including this portal similar issue but could not find any solution for my issue.
Solution
From official docs:
You may use a dedicated status field in your actions
Basically you need to dispatch action for each state to make an async action to work properly.
const searchQuery = () => {
return dispatch => {
dispatch({
type : 'START',
})
//make a get request to get the movies
axios.get(url)
.then((res) => {
dispatch({type : 'PASS', payload : res.data});
})
.catch((err) => {
dispatch({type : 'FAILED', payload : res.error});
});
}
With redux-thunk it's pretty simple to set up. You just have to make some changes to your store. Out the box, I'm pretty sure redux isn't the most friendly with async and that's why thunk is there.
import { ..., applyMiddleware } from "redux";
import thunk from "redux-thunk";
...
const store = createStore(reducer, applyMiddleware(thunk));
...
Then in your action you'll need to return dispatch which will handle your logic for your axios call.
const fetchMovie = () => {
return dispatch => {
const url = //Your url string here;
axios.get(url).then(res => {
dispatch(discoverMovie(res.data.results, res.status);
}).catch(err => {
//handle error if you want
});
};
};
export const discoverMovie = (results, status) => {
return {
type: DISCOVER_MOVIE,
payload: results,
status: status
};
};
Your reducer looks fine, though with the way my code is typed you'll have status separately. You can combine them into it's own object before returning in discoverMovie, if you need status with the results.
This is my first answer on stack so let me know if I can clarify anything better!

React Redux - Actions must be plain objects. Use custom middleware for async actions

I try to deal with ajax data using axom in my learning react,redux project and I have no idea how to dispatch an action and set the state inside a component
In component will mount
componentWillMount(){
this.props.actions.addPerson();
}
Store
import { createStore, applyMiddleware } from "redux";
import rootReducer from "../reducers";
import thunk from "redux-thunk";
export default function configureStore() {
return createStore(rootReducer, applyMiddleware(thunk));
}
In Action :
import * as types from "./action-types";
import axios from "axios";
export const addPerson = person => {
var response = [];
axios
.get(`&&&&&&&&&&&`)
.then(res => {
response = res.data;
return {
type: types.ADD_PERSON,
response
};
});
};
In reducer
import * as types from "../actions/action-types";
export default (state = [], action) => {
console.log("action======>", action);
switch (action.type) {
case types.ADD_PERSON:
console.log("here in action", action);
return [...state, action.person];
default:
return state;
}
};
I am getting Actions must be plain objects. Use custom middleware for async actions.
You should use dispatch for async function. Take a look of the redux-thunk's documentation: https://github.com/gaearon/redux-thunk
In Action:
import * as types from "./action-types";
import axios from "axios";
export const startAddPerson = person => {
return (dispatch) => {
return axios
.get(`https://599be4213a19ba0011949c7b.mockapi.io/cart/Cart`)
.then(res => {
dispatch(addPersons(res.data));
});
}
};
export const addPersons = personList => {
return {
type: types.ADD_PERSON,
personList
};
}
In PersonComponent:
class Person extends Component {
constructor(props){
super(props);
}
componentWillMount() {
this.props.dispatch(startAddPerson())
}
render() {
return (
<div>
<h1>Person List</h1>
</div>
);
}
}
export default Redux.connect()(Person);
You need two actions here: postPerson and addPerson.
postPerson will perform the API request and addPerson will update the store:
const addPerson = person => {
return {
type: types.ADD_PERSON,
person,
}
}
const postPerson = () => {
return (dispatch, getState) => {
return axios.get(`http://599be4213a19ba0011949c7b.mockapi.io/cart/Cart`)
.then(res => dispatch(addPerson(res.data)))
}
}
in your component, call postPerson()
You use the redux-thunk library which gives you access to the "getState" and "dispatch" methods. I see that that has been added by Chenxi to your question. Run your async operation first within your action and then call "dispatch" with your simple action action creator, which will return the simple object that redux is looking for.
Here is what your async action creator and your simple action creator(broken out into two action creators) will look like:
export const addPersonAsync = (person) => {
return (dispatch) => {
var response = [];
axios
.get(`http://599be4213a19ba0011949c7b.mockapi.io/cart/Cart`)
.then(res => {
response = res.data;
dispatch(addPerson(response));
});
};
};
export const addPerson = (response) => ({
type: types.ADD_PERSON,
response
});
From your component, you'll now call the "addPersonAsync" action creator.

react redux-thunk component doesn't render this.props

I'm new to react and I'm trying to understand on to make async ajax request. I was able to get the request completed and the data returned added to my state, but I can't render the data to my component. Here's my setup.
UserPage component
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import { getUsers } from '../../actions';
class User extends Component {
displayName: 'User';
componentWillMount() {
this.props.getUsers();
}
renderUsers() {
return this.props.users.map(user => {
return (
<h5>{user.Name}</h5>
);
});
}
render() {
var component;
if (this.props.users) {
component = this.renderUsers()
} else {
component = <h3>asdf</h3>;
}
return (
<div>
{component}
</div>
);
};
};
function mapStateToProps(state) {
return {
users: state.all
};
}
export default connect(mapStateToProps, { getUsers })(User);
Action
import request from '../helpers/request';
import { GET_USERS } from './types';
export function getUsers() {
return request.get(GET_USERS, 'Person/GetPeople');
}
With the get function from request.js module
get: function (action, url) {
return (dispatch) => {
axios.get(`${ROOT_URL}${url}`)
.then(({ data }) => {
dispatch({
type: action,
payload: data
});
});
};
}
User_reducer
import { GET_USERS } from '../actions/types';
export default function (state = {}, action) {
switch (action.type) {
case GET_USERS:
console.log(action);
return { ...state, all: action.payload }
default:
return state;
};
}
When I load the UserPage component, I can see the request being done and the state being updated in the redux dev tool, but I can't display this.props.users.
If I take out the if(this.props.users) in the render() method of the User component, I get an undefined on this.props.users.
What am I doing wrong?
Any help greatly appreciated! Thank you
SOLVED
The solution was to set the users property to state.users.all in the mapStateToProps function.
function mapStateToProps(state) {
return {
users: state.users.all
};
}
Thank you
Could you check, do you have this.renderUsers() defined in that render function? It might be you forgot to bind it, and that function is undefined?
Try to add this.renderUsers = this.renderUsers.bind(this); in your constructor and see, if it helps.

Categories

Resources