Component structure to handle Async Action with Redux-thunk ? - reactjs

After a bit of trial and error I finally manage to get my action creator working properly and passing the data I wanted into my redux store. Until now I've been dispatching it "manually" like this store.dispatch(fetchTest()); but It would be great if could use these data into a component.
So here is my action creator :
export const fetchTest = () => (dispatch) => {
dispatch({
type: 'FETCH_DATA_REQUEST',
isFetching:true,
error:null
});
return axios.get('http://localhost:3000/authors')
.then(data => {
dispatch({
type: 'FETCH_DATA_SUCCESS',
isFetching:false,
data: data
});
})
.catch(err => {
dispatch({
ype: 'FETCH_DATA_FAILURE',
isFetching:false,
error:err
});
console.error("Failure: ", err);
});
};
Here is my reducer :
const initialState = {data:null,isFetching: false,error:null};
export const ThunkData = (state = initialState, action)=>{
switch (action.type) {
case 'FETCH_DATA_REQUEST':
case 'FETCH_DATA_FAILURE':
return { ...state, isFetching: action.isFetching, error: action.error };
case 'FETCH_DATA_SUCCESS':
return Object.assign({}, state, {data: action.data, isFetching: action.isFetching,
error: null });
default:return state;
}
};
So far everything is working properly when using store.dispatch(fetchTest());.
Based on this example I tried to build the following component :
class asyncL extends React.Component {
constructor(props) {
super(props);
}
componentWillMount() {
this.props.fetchTest(this.props.thunkData)
// got an error here : "fetchTest is not a function"
}
render() {
if (this.props.isFetching) {
return console.log("fetching!")
}else if (this.props.error) {
return <div>ERROR {this.props.error}</div>
}else {
return <p>{ this.props.data }</p>
}
}
}
const mapStateToProps = (state) => {
return {
isFetching: state.ThunkData.isFetching,
data: state.ThunkData.data.data,
error: state.ThunkData.error,
};
};
const AsyncList = connect(mapStateToProps)(asyncL);
export default AsyncList
It doesn't work, I have an error on the componentWillMount() and probably somewhere else.
Also my data structure is kind of weird. To actually get to the data array I have to do state.ThunkData.data.data. The first data object is full of useless stuff like request, headers, etc...
So how should I write this component so I can at least passed the Async data into a console.log.
Thanks.

You need to mapDispatchToProps as well.
import { fetchTest } from './myFetchActionFileHere';
import { bindActionCreators } from 'redux';
function mapDispatchToProps(dispatch) {
return {
fetchTest: bindActionCreators(fetchTest, dispatch)
};
}
const AsyncList = connect(mapStateToProps, mapDispatchToProps)(asyncL);
export default AsyncList
documentation link: http://redux.js.org/docs/api/bindActionCreators.html

Related

Trying to get firebase data to load into component as state and then be edited

I'm struggling to get get data from Firebase to load into a form wizard.
The basic example I am trying right now is just to display some of the firebase data given the collection id.
The current error I am receiving is that there isn't the correct workflow id being parsed into the redux action.
This is the react component
import React from "react";
import PropTypes from "prop-types";
//Redux
import { connect } from "react-redux";
import { getWorkflow } from "../../redux/actions/dataActions";
const example = '3ejAQxPoJ6Wsqsby01S6';
class EoT extends React.Component {
componentDidMount() {
this.props.getWorkflow('3ejAQxPoJ6Wsqsby01S6');
}
render() {
const { Workflow} = this.props.data;
return (<div>
<p>Crazy</p>
<h4>{Workflow.createdAt}</h4>
</div>
);
}
}
EoT.propTypes = {
getWorkflow: PropTypes.func.isRequired,
data: PropTypes.object.isRequired
};
const mapStateToProps = state => ({
data: state.data
});
export default connect(mapStateToProps, {getWorkflow})(EoT);
I have another workflow piece of code that I am using but this is just to test I can load it at all,
this is my api query which works using postman.
// Get Workflow
export const getWorkflow = (WorkflowId) => dispatch => {
dispatch({ type: LOADING_DATA });
axios
.get(`/Workflow/${WorkflowId}`)
.then(res => {
dispatch({
type: SET_WORKFLOW,
payload: res.data
});
})
.catch(err => {
dispatch({
type: SET_WORKFLOW,
payload: []
});
});
};
This is the redux action I am using with that query
import {
SET_PROJECTS,
LOADING_DATA,
DELETE_PROJECT,
POST_PROJECT,
SET_PROJECT,
SET_CLAIMS,
SET_CLAIM,
DELETE_CLAIM,
POST_CLAIM,
SUBMIT_COMMENT,
SET_WORKFLOWS,
SET_WORKFLOW
} from "../types";
const initialStateProject = {
Projects: [],
Project: {},
Claims: [],
Claim: {},
Workflows: {},
Workflow: {},
loading: false
};
export default function(state = initialStateProject, action) {
switch (action.type) {
case LOADING_DATA:
return {
...state,
loading: true
};
case SET_WORKFLOWS:
return {
...state,
Workflows: action.payload,
loading: false
};
case SET_WORKFLOW:
return {
...state,
Workflow: action.payload
};
default:
return state;
}
}
Hope that helps explain the problem - I am currently wondering if I can place the id inside it somehow?
export const getWorkflow = () => dispatch => {
dispatch({ type: LOADING_DATA });
axios
.get("/Workflow/:WorkflowId")
:WorkflowId is not a valid reference here, you need to pass the WorkflowId in as a parameter to this thunk.
Ended up being that I had to call workflows and not workflow :D

mapStateToProps() in Connect() must return a plain object. Instead received undefined

I have a problem with displaying data.
In my application I use react and redux.
In the console I will get an error mapStateToProps() in Connect(ListPets) must return a plain object. Instead received undefined.
This is my main component
import React, { Component } from 'react';
import { connect } from 'react-redux';
import loadData from '../actions/actions';
class ListPets extends Component {
componentDidMount() {
const { loadData } = this.props;
loadData();
console.log(loadData );
}
render() {
const { dataPet } = this.props;
return (
<div>
</div>
);
}
}
const mapStateToProps = (state) => {
return state;
};
const mapDispatchToProps = (dispatch) => {
return {
loadData: () => dispatch(loadData())
}
};
This fragment console.log(loadData ); display
ƒ loadData() {
return dispatch(Object(_actions_actions__WEBPACK_IMPORTED_MODULE_7__["default"])());
}
When I add the code {dataPet.data} in div. I get an error]. As if this data was not in the store, I do not know...
this my reducer function
const initialState = {
isFetching: false,
dataPet: [],
};
const fetchDataReducer = (state=initialState, action) => {
switch(action.types) {
case actionTypes.FETCH_DATA_START:
return {
...state,
isFetching: true,
}
case actionTypes.FETCH_DATA_SUCCESS:
return {
...state,
isFetching: false,
dataPet: action.dataPet,
}
case actionTypes.FETCH_DATA_FAIL:
return {
...state,
isFetching: false,
}
};
}
Data is well downloaded, because the console receives the FETCH_DATA_SUCCESS action.
I have no idea how to solve this problem
I made some changes on your code, try this now...should work
https://codesandbox.io/s/z2volo1n6m
In your reducer you have a typo:
const fetchDataReducer = (state=initialState, action) => {
switch(action.types) { // here
It should be action.type not action.types.
If thing is an object in state:
const mapStateToProps = state => ({
thing: state.thing,
});
Then use like:
this.props.thing in your component

Component isn't updating after state change

I have read through 100's of these threads on here, and I can't seem to understand why my component isn't updating. I am pretty sure it has something to do with the Immutability, but I can't figure it out.
The call is being made, and is returning from the server. The state is changing (based on the redux-Dev-Tools that I have installed).I have made sure to not mutate the state in any instance, but the symptoms seem to point that direction.
Code Sandbox of whole app https://codesandbox.io/s/rl7n2pmpj4
Here is the component.
class RetailLocationSelector extends Component {
componentWillMount() {
this.getData();
}
getData = () => {
this.props.getRetailLocations()
}
render() {
const {data, loading} = this.props;
return (
<div>
{loading
? <LinearProgress/>
: null}
<DefaultSelector
options={data}
placeholder="Retail Location"/>
</div>
);
}
}
function mapStateToProps(state) {
return {
loading: state.retaillocations.loading,
data: state.retaillocations.data,
osv: state.osv};
}
function mapDispatchToProps(dispatch) {
return bindActionCreators({
getRetailLocations,
selectRetailLocation,
nextStep
}, dispatch);
}
export default connect(mapStateToProps, mapDispatchToProps)(RetailLocationSelector);
And here is my reducer :
import {REQUEST_RETAIL_LOCATIONS, SUCCESS_RETAIL_LOCATIONS,
ERR_RETAIL_LOCATIONS, SELECT_RETAIL_LOCATION} from
'../actions/RetailLocationsAction'
const initialState = {
data: [],
loading: false,
success: true,
selectedRetailLocation: undefined
}
function retailLocation(state = initialState, action) {
switch (action.type) {
case REQUEST_RETAIL_LOCATIONS:
return Object.assign({}, state, {
loading: true
}, {success: true})
case SUCCESS_RETAIL_LOCATIONS:
return Object.assign({}, state, {
loading: false
}, {
success: true
}, {
data: Object.assign([], action.payload.data)
})
case ERR_RETAIL_LOCATIONS:
return Object.assign({}, state, {
loading: false
}, {
success: false
}, {errorMsg: action.payload.message})
case SELECT_RETAIL_LOCATION:
return Object.assign({}, state, {
selectedRetailLocation: state
.data
.find((rec) => {
return rec.id === action.payload.id
})
})
default:
return state;
}
}
export default retailLocation
And finally, my Action file:
import axios from 'axios';
//import {api} from './APIURL'
export const REQUEST_RETAIL_LOCATIONS = 'REQUEST_RETAIL_LOCATIONS'
export const SUCCESS_RETAIL_LOCATIONS = 'SUCCESS_RETAIL_LOCATIONS'
export const ERR_RETAIL_LOCATIONS = 'ERR_RETAIL_LOCATIONS'
export const SELECT_RETAIL_LOCATION = 'SELECT_RETAIL_LOCATION'
const URL = 'localhost/api/v1/retail/locations?BusStatus=O&LocType=C'
export const getRetailLocations = () => (dispatch) => {
dispatch({ type: 'REQUEST_RETAIL_LOCATIONS' });
return axios.get(URL)
.then(data => dispatch({ type: 'SUCCESS_RETAIL_LOCATIONS', payload: data }))
.catch(error => dispatch({type : 'ERR_RETAIL_LOCATIONS', payload: error}));
}
Combined Reducer
import { combineReducers } from "redux";
import retailLocations from './RetailLocationsReducer'
import vendors from './VendorsReducer'
import receiptInformation from './ReceiptInfoReducer'
import osv from './OSVReducer'
import receiptDetail from './ReceiptDetailReducer'
const allReducers = combineReducers({
retaillocations: retailLocations,
vendors: vendors,
receiptInformation: receiptInformation,
receiptDetail: receiptDetail,
osv: osv
});
export default allReducers;
This answer doesn't solve your issue totally but provides some hints about what is not working. The broken part is your store definition. I don't have much experience with redux-devtools-extension or redux-batched-subscribe but if you define your store like that your thunk function works:
const store = createStore(reducer, applyMiddleware(thunk));
One of the configuration for the mentioned packages above brokes your thunk middleware.

State is undefined in mapStateToProps

I've been trying to retrieve the new state from my vitaminReducer() reducer function, and connect it through mapStateToProps. But when I console.log the state, I get back "the state is {vitamin: undefined}".
This is the Vitamins component where I'm calling mapStateToProps()
(Vitamins.js)
componentDidMount() {
this.props.fetchVitamins();
}
function mapStateToProps(state) {
return {
vitamin: state,
}
};
console.log('the state is', mapStateToProps());
export default connect(mapStateToProps, { fetchVitamins })(Vitamins);
(reducers.js)
function vitaminReducer(state = [], action) {
switch(action.type) {
case FETCH_VITAMINS_SUCCESS:
return [
...state,
action.payload.vitamins
];
default:
return state;
}
}
const reducers = combineReducers({
vitamin: vitaminReducer,
});
I have the data coming through an Express server. I've console logged "vitamins" here and I get the data back, so I know that's not the issue.
(actions.js)
export function fetchVitamins() {
return dispatch => {
return fetch("/users")
.then(handleErrors)
.then(res => res.json())
.then(micros => {
dispatch(fetchVitaminsSuccess(micros));
const vitamins = micros.vitamins;
}
)};
};
export const FETCH_VITAMINS_SUCCESS = 'FETCH_VITAMINS_SUCCESS';
export const fetchVitaminsSuccess = vitamins => ({
type: FETCH_VITAMINS_SUCCESS,
payload: vitamins
});
If I do: "return { vitamin: state.vitamin, }" instead of "return { vitamin: state, }", I get back "TypeError: Cannot read property 'vitamin' of undefined". But that's what I called vitaminReducer in my combineReducers() function at the bottom of reducers.js, so I thought that was the right way to do it.
Thank you everyone for your input! I was able to get it working.
I ditched the mapStateToProps() and instead did this
(Vitamins.js)
componentDidMount() {
this.props.fetchVitamins();
}
renderData() {
const { vitamins } = this.props.vitamins;
return vitamins.map((micro, index) => {
return (
<option value={micro.value} key={index}>{micro.name}</option>
)
})
}
export default connect(
state => ({
vitamins: state.vitamins
}),
{
fetchVitamins
},
)(Vitamins);
I set the dispatch action inside of the fetchVitamins() function
(actions.js)
export function fetchVitamins() {
return dispatch => {
return fetch("/users")
.then(handleErrors)
.then(res => res.json())
.then(micros => {
dispatch({
type: "RECEIVE_VITAMINS",
payload: micros.vitamins
});
}
)};
};
export const RECEIVE_VITAMINS = 'RECEIVE_VITAMINS';
In reducers I set the initialState to the vitamins array, and passed the new state of micros.vitamins from my RECEIVE_VITAMINS action
(reducers.js)
const initialState = {
vitamins: [],
}
function vitaminReducer(state = initialState, action) {
switch(action.type) {
case RECEIVE_VITAMINS:
return {
...state,
vitamins: action.payload
};
default:
return state;
}
}
const reducers = combineReducers({
vitamins: vitaminReducer,
});
Thanks everyone for your help! Let me know if you have any other suggestions :D

Redux - mapDispatchToProps - TypeError: _this.props.setCurrentUserHandle is not a function

I am trying to get a simple react-redux app to work and I am running into a weird error that I can't figure out. I am trying to simply set my current user's first name and handle the store and one set function works and the other doesn't.
setCurrentUserFirstName - works
setCurrentUserHandle - doesn't
import React, { Component } from 'react';
import { Link } from 'react-router';
import { connect } from 'react-redux';
import store from '../../store';
var Utilities = require('../../../common/commonutilities.js');
var RestClient = require('../../../common/restClient.js');
//actions
import { setCurrentUserHandle, setCurrentUserFirstName } from '../../actions/userActions';
class Header extends Component {
constructor(props) {
super(props);
this.state = {};
RestClient.api.fetchGet('/getcurrentuser', (response) => {
if(response.success) {
this.setState({
isAuthenticated: true,
currentUser: response.currentUser
});
store.dispatch({
type: 'USER_DID_LOGIN',
userLoggedIn: true
});
//works fine
this.props.setCurrentUserFirstName(response.currentUser.firstName);
//doesn't work and throws the error: "TypeError: _this.props.setCurrentUserHandle is not a function"
this.props.setCurrentUserHandle(response.currentUser.handle);
}
},
(err) => {
console.log(err);
});
}
render() {
return (
{this.props.user.currentUserFirstName}, {this.props.user.currentUserHandle}
);
}
}
const mapStateToProps = function(store) {
return {
//user properties
user: store.userState
};
};
const mapDispatchToProps = (dispatch) => {
return{
setCurrentUserFirstName: (currentUserFirstName) =>{
dispatch( setCurrentUserFirstName(currentUserFirstName));
}
}
return{
setCurrentUserHandle: (currentUserHandle) =>{
dispatch( setCurrentUserHandle(currentUserHandle));
}
}
};
//connect it all
export default connect(mapStateToProps, mapDispatchToProps)(Header);
I have them as actions in the userActions.js file
export function setCurrentUserFirstName(currentUserFirstName){
return{
type: 'SET_CURRENT_USER_FIRST_NAME',
payload: currentUserFirstName
};
}
export function setCurrentUserHandle(currentUserHandle){
return{
type: 'SET_CURRENT_USER_HANDLE',
payload: currentUserHandle
};
}
And in the reducer
const initialUserState = {
user: {},
currentUserFirstName:[],
currentUserHandle:[]
};
// The User reducer
const userReducer = (state = initialUserState, action) => {
//using newState object to be immutable
let newState = state;
switch (action.type) {
case 'SET_CURRENT_USER_FIRST_NAME':
newState = {
...state,
currentUserFirstName: action.payload
};
break;
case 'SET_CURRENT_USER_HANDLE':
newState = {
...state,
currentUserHandle: action.payload
};
break;
break;
default:
break;
}
return newState;
};
export default userReducer;
What do I have incorrect?
You have 2 return statements in your mapDispatchToProps - the second one will never be reached. You can return a single object as follows:
const mapDispatchToProps = (dispatch) => {
return{
setCurrentUserFirstName: (currentUserFirstName) =>{
dispatch( setCurrentUserFirstName(currentUserFirstName));
},
setCurrentUserHandle: (currentUserHandle) =>{
dispatch( setCurrentUserHandle(currentUserHandle));
}
}
};
In addition to Tony's correct answer, I highly encourage that you use the "object shorthand" form of mapDispatch instead. You can pass an object full of action creators as the second argument to connect(), instead of an actual mapDispatch function. In your case, it'd look like:
import { setCurrentUserHandle, setCurrentUserFirstName } from '../../actions/userActions';
const actionCreators = { setCurrentUserHandle, setCurrentUserFirstName };
class Header extends Component {}
export default connect(mapStateToProps, actionCreators)(Header);

Resources