React Redux how to dispatch async actions and update state - reactjs

I try to deal with ajax data in my learning react,redux project and I have no idea how to dispatch an action and set the state inside a component
here is my component
import React, {PropTypes, Component} from 'react';
import Upload from './Upload';
import {bindActionCreators} from 'redux';
import {connect} from 'react-redux';
import * as profileActions from '../../../actions/profileActions';
class Profile extends Component {
static propTypes = {
//getProfile: PropTypes.func.isRequired,
//profile: PropTypes.object.isRequired,
};
constructor(props) {
super(props);
this.state = {
profile:{
username: '',
password: ''
}
}
this.onUpdate = this.onUpdate.bind(this)
}
onUpdate(event) {
alert()
}
componentWillMount() {
}
componentDidMount() {
}
render() {
const {profile} = this.props;
return (
<div>
</div>
);
}
}
function mapStateToProps(state) {
console.log(state)
return {
profile: state.default.profile,
};
}
function mapDispatchToProps(dispatch, ownProps) {
return {
actions: bindActionCreators(profileActions, dispatch)
};
}
export default connect(mapStateToProps, mapDispatchToProps)(Profile);
I create the store as it follows
import { createStore, combineReducers, applyMiddleware } from 'redux'
import createLogger from 'redux-logger'
import thunk from 'redux-thunk'
import { routerReducer, routerMiddleware, push } from 'react-router-redux'
import reducers from '../reducers'
import { browserHistory } from 'react-router';
const middleware = [ thunk ];
if (process.env.NODE_ENV !== 'production') {
middleware.push(createLogger());
}
middleware.push(routerMiddleware(browserHistory));
// Add the reducer to your store on the `routing` key
const store = createStore(
combineReducers({
reducers,
routing: routerReducer
}),
applyMiddleware(...middleware),
)
export default store;
reducer
export const RESOLVED_GET_PROFILE = 'RESOLVED_GET_PROFILE'
const profileReducer = (state = {}, action) => {
switch (action.type) {
case 'RESOLVED_GET_PROFILE':
return action.data;
default:
return state;
}
};
export default profileReducer;
actions
import * as types from './actionTypes';
import Api from '../middleware/Api';
export function getProfile() {
return dispatch => {
dispatch(setLoadingProfileState()); // Show a loading spinner
Api.getAll('profile').then(profile => {
dispatch(doneFetchingProfile(profile));
}).catch(error => {
throw(error);
});
/*Api.fetch(`profile`, (response) => {
console.log(response)
dispatch(doneFetchingBook()); // Hide loading spinner
if(response.status == 200){
dispatch(setProfile(response.json)); // Use a normal function to set the received state
}else {
dispatch(error)
}
}) */
}
}
function setProfile(data) {
return {type: types.SET_PROFILE, data: data}
//return { type: types.SET_PROFILE, data: data };
}
function setLoadingProfileState() {
return {type: types.SHOW_SPINNER}
}
function doneFetchingProfile(data) {
console.log(data)
return {
type: types.HIDE_SPINNER,
profile: data
}
}
function error() {
return {type: types.SHOW_ERROR}
}
but I have no idea how would I dispatch action and update the state after getProfile action

You need to only dispatch your event RESOLVED_GET_PROFILE right after dispatching doneFetchingProfile, or simply listen RESOLVED_GET_PROFILE and hide spinner on reducing it.
Api.getAll('profile').then(profile => {
dispatch(doneFetchingProfile(profile));
dispatch(resoloveGetProfile(profile));
})
Actually you r doing everything right - so I didn't understand what is your question is, so if you meant something else - let me know, I`ll try to describe you.
About dispatch(resoloveGetProfile(profile));
There you dispatch action, which will update your state, simple as you do with some static state, I saw that you already have setProfile action, so you can change that line, to call your existed function.
dispatch(setProfile(profile))
Than you need to reduce your state in this action
case 'SET_PROFILE' : (action, state) => {...state, profile: action.data}
Than your state will change and your components will update. Note that your 'get profile method' better to call from componentDidMount to avoid freezing at rendering because of performing web request.

Related

How to use redux in Next.js?

I am new to Next.js, So I follow some tutorials for Redux integration in Next.js. All is working fine but whenever I switch between pages, each time API make a call, and Redux lost its stored value.
The basic function is like this. Whenever a user loads a website an API call will fetch category data from the server and save that data in reducer[categoryReducer], then the user can navigate to any page and category data will fetched from the reducer. But in my case, it hits again and again
Full Code:
// Action Call
import * as Constants from '../../constant/constant';
import * as t from '../types';
import axios from 'axios';
export const loadCategoryApi = (type) => dispatch => {
axios.post(Constants.getCategories,type)
.then(function (response) {
console.log(response);
if(response && response.data && response.data.status==="200"){
dispatch({
type: t.LOAD_CATEGORY,
value: type
});
}
else if(response && response.data && response.data.status==="404"){
alert('Someting went wrong');
}
})
}
// Reducer File
import * as t from '../types';
const initialState = {
doc:null
}
const CategoryReducer = (state = initialState, action) =>{
console.log('reducer action', action.type);
switch (action.type){
case t.LOAD_CATEGORY:
console.log('slots actions',action);
return({...state, doc:action.value})
default:
return state;
}
}
export default CategoryReducer;
// Store file
import { createStore, applyMiddleware, compose } from "redux"
import thunk from "redux-thunk"
import { createWrapper } from "next-redux-wrapper"
import rootReducer from "./reducers/rootReducer"
const middleware = [thunk]
const makeStore = () => createStore(rootReducer, compose(applyMiddleware(...middleware)))
export const wrapper = createWrapper(makeStore);
// rootReducer
import { combineReducers } from "redux"
import CategoryReducer from "./CategoryReducer";
const rootReducer = combineReducers({
CategoryReducer: CategoryReducer
})
export default rootReducer;
// _app.js
import React from "react"
import { wrapper } from "../redux/store"
import Layout from '../components/Layout';
import '../styles/globals.css'
const MyApp = ({ Component, pageProps }) =>(
<Layout>
<Component {...pageProps} />
</Layout>
);
export default wrapper.withRedux(MyApp);
// Uses
import React, { useState, useEffect } from 'react';
import {connect} from "react-redux";
import {loadCategoryApi} from "../redux/actions/CategoryAction";
function navbar(props){
const { loadCategory, loadCategoryApi } = props;
useEffect(() => {
if(loadCategory===null){
console.log('navbar loading funciton');
loadCategoryFunation();
}
}, []);
const loadCategoryFunation = () =>{
var json = {
type : 'main'
};
loadCategoryApi(json);
}
}
const mapStateToProps = state => {
return { loadCategory: state.CategoryReducer.doc }
}
const mapDispatchToProps = {
loadCategoryApi
}
export default connect(mapStateToProps, mapDispatchToProps)(Navbar)
What I am doing wrong?
You have to create main reducer to handle the hydration. I explained this hydration process here.
In the file that you created the store, write main reducer
import reducers from "./reducers/reducers";
const reducer = (state, action) => {
// hydration is a process of filling an object with some data
// this is called when server side request happens
if (action.type === HYDRATE) {
const nextState = {
...state,
...action.payload,
};
return nextState;
} else {
// whenever we deal with static rendering or client side rendering, this will be the case
// reducers is the combinedReducers
return reducers(state, action);
}
};
then pass this reducer to the store

React-Redux async functions using thunk not working

Types.js File:
const ADD_TOKENS = "ADD_TOKENS";
export { ADD_TOKENS};
Actions.js File:
import { ADD_TOKENS } from "./types";
function addTokens() {
return {
type: ADD_TOKENS,
};
}
const actionCreators = {
addTokens,
};
export { actionCreators };
Reducers.js File
import { ADD_TOKENS } from "./types";
import getTokens from "../../api/getTokens";
const initialState = {
access_token: null,
refresh_token: null,
expiration_time: null,
};
function applyAddTokens(state) {
console.log("Function being hit"); //yes
return async (dispatch) => {
console.log("Function being hit"); //no
const token = await getTokens();
return {
...state,
access_token: dispath(token.access_token),
refresh_token: dispath(token.refresh_token),
expiration_time: dispath(token.expiration_time),
};
};
}
function reducer(state = initialState, action) {
switch (action.type) {
case ADD_TOKENS:
return applyAddTokens(state);
default:
return state;
}
}
export default reducer;
index.js File
import React, { Component } from "react";
import { View, Text, TouchableOpacity } from "react-native";
import { connect } from "react-redux";
import { bindActionCreators } from "redux";
import { actionCreators as actions } from "./actions";
class Login extends Component {
render() {
const { addTokens } = this.props;
console.log("Props in Login/index.js", this.props);
return (
<View>
<TouchableOpacity onPress={addTokens}>
<Text>Login</Text>
</TouchableOpacity>
</View>
);
}
}
function mapStateToProps(state) {
const { access_token, refresh_token, expiration_time } = state;
return {
access_token,
refresh_token,
expiration_time,
};
}
function mapDispatchToProps(dispatch) {
return {
addTokens: bindActionCreators(actions.addTokens, dispatch)
};
}
export default connect(mapStateToProps, mapDispatchToProps)(Login);
store.js File
import { createStore, applyMiddleware } from "redux";
import thunk from "redux-thunk";
import reducer from "../components/Login/reducers";
const store = createStore(reducer, applyMiddleware(thunk));
export default store;
Why is this not working? Why is applyAddTokens function's thunk not producing anything? Let me know if anyone needs any additional details. getTokens() returns an object that contains access_token, refresh_token, and expiration_time. This worked before when I tried it without async (just regular data without any request).
Your code flow is like below:
In your JSX, upon onPress, you trigger the action addTokens.
This action returns an object of type ADD_TOKENS
Redux will directly execute the reducer (the ADD_TOKENS switch case). Here you are calling an async function applyAddTokens.
Redux will execute it IMMEDIATELY (without waiting for promise result) and returns the output of applyAddTokens function which is a pending promise
That's it.
Solution
First, put all async code in your actions. Keep reducers light and use it only to update state.
To use thunk, your action must return a function (not an object).
See this example as well

How to dispatch multiple actions from redux action creators / thunk

In a small React/Redux app that I am writing, I have a thunk that looks as follow:
updateCategory(category){
return function(dispatch, getState){
dispatch({ type : types.UPDATE_CATEGORY, category });
dispatch({ type : locationTypes.UPDATE_CATEGORY_FOR_ALL_LOCATIONS, category });
}
}
complete code:
//Category Duck
import v4 from 'node-uuid';
import {types as locationTypes} from './locations'
export const types = {
UPDATE_CATEGORY:"UPDATE_CATEGORY"
};
const initialState = [];
export function reducer(state = initialState, action){
switch (action.type) {
case types.UPDATE_CATEGORY:
return state.map( item => item.id !== action.category.id ? item : {...action.category} );
default:
return state;
}
};
export const actions={
updateCategory(category){
return function(dispatch, getState){
dispatch({ type : types.UPDATE_CATEGORY, category });
dispatch({ type : locationTypes.UPDATE_CATEGORY_FOR_ALL_LOCATIONS, category });
}
}
}
//Location Duck
import v4 from 'node-uuid';
export const types = {
UPDATE_CATEGORY_FOR_ALL_LOCATIONS:"UPDATE_CATEGORY_FOR_ALL_LOCATIONS"
};
const initialState=[];
export function reducer(state = initialState, action){
switch (action.type) {
case types.UPDATE_CATEGORY_FOR_ALL_LOCATIONS:
return state.map(item => item.category.id !== action.category.id ? item : { ...item, 'category':{name:action.category.name, id:action.category.id} })
default:
return state;
}
};
export const actions={
updateCategoryForAllLocations(category){
return { type : types.UPDATE_CATEGORY_FOR_ALL_LOCATIONS, category}
}
}
//configStore
import { createStore, combineReducers, applyMiddleware, compose } from 'redux';
import { routerReducer, routerMiddleware } from 'react-router-redux';//, push
import logger from 'redux-logger';
import * as storage from './localstorage';
import throttle from 'lodash/throttle';
import reducers from './duckes/rootReducer'; // Or wherever you keep your reducers
import thunk from 'redux-thunk';
const persistedState = storage.loadState();
const configureStore = (history) => {
const store = createStore(
combineReducers({
...reducers,
// router: routerReducer
}),
persistedState,
applyMiddleware(thunk)
);
store.subscribe(throttle(() => {
storage.saveState( store.getState() )
}),1000);
return store;
}
export default configureStore;
when calling it from a UI click handler in a connected component like this:
updateCategory({id:1, name:'foo')
I get back Error: Actions must be plain objects. Use custom middleware for async actions.
Can you advice me on how to solve this or maybe explain why it is happening?
the component with the call looks as follows:
/ManageCategoryPage
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import {bindActionCreators} from 'redux';
import {connect} from 'react-redux';
import {actions as categoryActions} from '../../duckes/categories';
import CategoryForm from './CategoryForm';
import {getElementByID} from '../../utils';
class ManageCategoryPage extends Component {
constructor(props) {
super(props);
//Init state
this.state = {
'category' : Object.assign({},this.props.category),
'errors':{}
}
//Bind functions
this.saveCategory=this.saveCategory.bind(this);
this.updateCategoryState=this.updateCategoryState.bind(this);
this.categoryExists=this.categoryExists.bind(this);
}
updateCategoryState(event){
...
}
categoryExists(category){
...
}
saveCategory(event){
event.preventDefault();
const {category}=this.state;
this.props.actions.updateCategory(category);
this.props.history.push('/categories');
}
//Render
render(){
return (
<CategoryForm
category={this.state.category}
locations={this.props.locations}
onChange={this.updateCategoryState}
onSave={this.saveCategory}
errors={this.state.errors}/>
)
}
}
//Prop Types validation
ManageCategoryPage.propTypes={
category: PropTypes.object.isRequired,
locations: PropTypes.array.isRequired,
categories: PropTypes.array.isRequired,
actions: PropTypes.object.isRequired
};
//Redux connect
const mapStateToProps = ({locations, categories}, ownProps) => {
let category={id:'', name:''};
return {
category : getElementByID(categories, ownProps.match.params.id) || category,
locations : locations,
categories : categories
};
};
const mapDispatchToProps = (dispatch) => {
return {
'actions': bindActionCreators(categoryActions, dispatch)
};
};
export default connect(mapStateToProps, mapDispatchToProps)(ManageCategoryPage);
I have found the issue and actually it was a mistake of mine, I had two configStore files and I somehow imported an old version of the configStore file that i created previously and it was missing 'thunk' as a param in applyMiddleware() call, so it means that it was applyMiddleware() instead applyMiddleware(thunk).

Components not having the expected props, while React and Redux Dev Tools are having the expected States and Props

I am learning react-redux, so I decided to implement what I have been learning. But I am have a bug challenge. So I console.logged this.props.users from mapStateToProps function.
I believe there's something I not doing right which I don't understand. Please an explanation in other to move on. Thanks you so much for helping out.
Here is my code.
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { fetchUsers } from '../actions/userAction';
import UserList from '../components/UserList';
class UserPage extends Component {
constructor(props) {
super(props);
}
componentWillMount() {
this.props.fetchUsers();
}
componentDidMount() {
console.log(this.props.users);
}
render() {
return (
<div>
<h2>Users Page</h2>
<UserList users={this.props.users} />
</div>
);
}
}
const mapStateToProps = state => {
return {
users: state.userReducer.users
};
};
const mapDispatchToProps = dispatch => {
return {
fetchUsers: () => dispatch(fetchUsers())
};
};
export default connect(mapStateToProps, mapDispatchToProps)(UserPage);
So this is what I get from the chrome console - Empty arrays.
props showing empty arrays
But when I check the React DevTool and Redux DevTool, they display the expected Props and States respectively. Below are the snapshot of the dev tools
React devtool shows the correct Props
Redux devtool show the correct States and Actions
userAction.js
import axios from 'axios';
import * as types from './actionTypes';
export let fetchingUser = () => {
return {
type: types.FETCHING_USERS
};
};
export let fetchedUser = payload => {
return {
type: types.FETCHED_USER,
payload
};
};
export let fetchUser_error = () => {
return {
type: types.FETCH_USER_ERROR
};
};
export let fetchUsers = () => {
let url = 'https://eventcity.herokuapp.com/api/v1/users';
return dispatch => {
dispatch(fetchingUser());
return axios
.get(url)
.then(response => {
const users = response.data.data;
dispatch(fetchedUser(users));
})
.catch(err => {
dispatch(fetchUser_error());
});
};
};
userReducer.js
import * as types from '../actions/actionTypes';
import initialState from './initialState';
const userReducer = (state = initialState, action = {}) => {
switch (action.type) {
case types.FETCHING_USERS:
return { ...state, users: [], error: null, loading: true };
case types.FETCHED_USER:
return { ...state, users: action.payload, error: null, loading: false };
case types.FETCH_USER_ERROR:
return {
...state,
users: [],
error: { message: 'Error loading data from the API' },
loading: false
};
default:
return state;
}
};
export default userReducer;
configureStore.js
import { createStore, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';
import { composeWithDevTools } from 'redux-devtools-extension';
import rootReducer from '../reducer/rootReducer';
const configureStore = () => {
return createStore(rootReducer, composeWithDevTools(applyMiddleware(thunk)));
};
export default configureStore;
rootReducer.js
import { combineReducers } from 'redux';
import userReducer from './userReducer';
const rootReducer = combineReducers({
userReducer
});
export default rootReducer;
I think you might want to check this
https://github.com/reactjs/react-redux/issues/129. Your problem is using componentDidMount and componentWillMount without having a better understanding of what they are used for.
The problem is not with redux, all you need to understand is that your fetchUsers request is async and componentDidMount function is only executed once after the component has rendered and it may so happen that the data is not present by the time componentDidMount function is executed and hence your console.log(this.props.users); return empty array, Log it in the render method and you will see the correct data
class UserPage extends Component {
constructor(props) {
super(props);
}
componentWillMount() {
this.props.fetchUsers();
}
render() {
console.log(this.props.users);
return (
<div>
<h2>Users Page</h2>
<UserList users={this.props.users} />
</div>
);
}
}

react with redux and react-router dispatches action twice

I just started to experiment with react and redux and I face couple of issues on the way.
When I try to render async data on route change the dispatched action is getting fired twice. First is undefined and than comes the real data.
Here is my store
import { createStore, combineReducers, applyMiddleware } from 'redux'
import createLogger from 'redux-logger'
import thunk from 'redux-thunk'
import { routerReducer, routerMiddleware, push } from 'react-router-redux'
import reducers from '../reducers'
import { browserHistory } from 'react-router';
const middleware = [ thunk ];
if (process.env.NODE_ENV !== 'production') {
middleware.push(createLogger());
}
middleware.push(routerMiddleware(browserHistory));
// Add the reducer to your store on the `routing` key
const store = createStore(
combineReducers({
reducers,
routing: routerReducer
}),
applyMiddleware(...middleware),
)
export default store;
reducer
export const RESOLVED_GET_PROFILE = 'RESOLVED_GET_PROFILE'
const profileReducer = (state = {}, action) => {
switch (action.type) {
case 'SET_PROFILE':
return {profile: action.profile}
default:
return state;
}
};
export default profileReducer;
actions
import * as types from './actionTypes';
import Api from '../middleware/Api';
export function getProfile() {
return dispatch => {
dispatch(setLoadingProfileState()); // Show a loading spinner
Api.get('profile').then(profile => {
dispatch(doneFetchingProfile);
dispatch(setProfile(profile));
}).catch(error => {
dispatch(showError(error));
throw(error);
});
}
}
function setProfile(data) {
return {
type: types.SET_PROFILE,
profile: data
}
}
function setLoadingProfileState() {
return {
type: types.SHOW_SPINNER,
loaded: false
}
}
function doneFetchingProfile() {
return {
type: types.HIDE_SPINNER,
loaded: true
}
}
function showError() {
return {
type: types.SHOW_ERROR,
loaded: false,
error: 'error'
}
}
and here is my component
import React, {PropTypes, Component} from 'react';
import {bindActionCreators} from 'redux';
import {connect} from 'react-redux';
import * as profileActions from '../../../actions/profileActions';
class Profile extends Component {
static propTypes = {
profile: PropTypes.object.isRequired,
};
constructor(props) {
super(props);
this.state = {
profile:{
username: '',
password: '',
email: ''
}
}
this.onUpdate = this.onUpdate.bind(this)
}
onUpdate(event) {
alert()
}
componentDidMount() {
//here I dispatch the action
this.props.actions.getProfile()
}
componentWillReceiveProps(nextProps) {
}
render() {
console.log(this.props)
//this.props.profile on first is undefined and then filled
const { profile } = this.props.profile
return (
<div>
</div>
);
}
}
function mapStateToProps(state) {
return {
profile: state.default.profile,
};
}
function mapDispatchToProps(dispatch) {
return {
actions: bindActionCreators(profileActions, dispatch)
};
}
export default connect(mapStateToProps, mapDispatchToProps)(Profile);
what do I wrong?
You said //this.props.profile on first is undefined and then filled
That's because in the first render, state.profile is undefined, until the request response arrives and the setProfile action is dispatched.
There's also the problem Andrew noted that you're calling dispatch(doneFetchingProfile). Since you're using redux-thunk, that will trigger calling doneFetchingProfile(dispatch, getState), but the action HIDE_SPINNER will never get dispatched.
UPDATE: There's nothing wrong with your code. You can see before SHOW_SPINNER the output of console.log(this.props) and there's no profile because there's no profile in state as well.
Then when your request succeeds, profile is set in state, then passed to your component and then you can see in the log that profile is set. Those are not actions dispatched, this is the log of your props.
The first time is undefined because the initial state declared in the reducer is {} (there's no profile here as well).
If you change
const profileReducer = (state = {}, action) => {
to
const profileReducer = (state = {profile: 'some initial value'}, action) => {
you'll see that the first console.log(this.props) will show profile with the value 'some initial value' and then change to the remote data.
This is what happening here
Your component render and show undefined on console because there is no profile data so far.
After component mount it call componentDidmount which fire an action to fetch data from url.
You get data from api and update the redux state which update your component as well.
Therefore you render function is called again and this time it shows the profile data.
There is nothing dispatching two times. The code is perfectly fine.
You dispatching 2 actions
dispatch(doneFetchingProfile);
dispatch(setProfile(profile));
First of them have no data, and it's look like tihs action set to state some data and update your component.

Resources