Props not loaded on initial render from redux store - reactjs

I am new to reactjs and need some help.
thanks for taking the time to solve my issue.
I am trying to get the data from props after authenticating a user from Signin page .
so when I get to home page the props does not give me the data in "auth" on initial render but automatically renders again and gives me the data.
I need the data on initial render or else the page crashes due to user data in the home page not being present
signin.js
class Signin extends Component {
state = { isSignedIn: false,
user: [] }
uiConfig = {
signInFlow: "popup",
signInOptions: [
firebase.auth.GoogleAuthProvider.PROVIDER_ID,
],
callbacks: {
signInSuccess: () => false
}
}
componentDidMount = () => {
firebase.auth().onAuthStateChanged(user => {
this.setState({ isSignedIn: !!user,
user})
console.log("state user is", this.state.user)
console.log("user on firebase", user)
})
}
render(){
const { authError, auth } = this.props;
if (auth.uid) return <Redirect to='/home' />
const signingin = (
this.state.isSignedIn ? (
<span>
<h1>signedin</h1>
</span>
) : (
<StyledFirebaseAuth
uiConfig={this.uiConfig}
firebaseAuth={firebase.auth()}
/>
))`
return (
<div>{signingin}
</div>
)
}
}
const mapStateToProps = (state) => {
return{
authError: state.auth.authError,
auth: state.firebase.auth
}
}
const mapDispatchToProps = (dispatch) => {
return {
signIn: (creds) => dispatch(signIn(creds)),
signOut: () => dispatch(signOut())
}
}
export default connect(mapStateToProps, mapDispatchToProps)(Signin);
authActions.js
export const signIn = (credentials) => {
return (dispatch, getState, {getFirebase}) => {
const firebase = getFirebase();
firebase.auth()(
credentials.email,
credentials.password
).then(() => {
dispatch({ type: 'LOGIN_SUCCESS' });
}).catch((err) => {
dispatch({ type: 'LOGIN_ERROR', err });
});
}
}
export const signOut = () => {
return (dispatch, getState, {getFirebase}) => {
const firebase = getFirebase();
firebase.auth().signOut().then(() => {
dispatch({ type: 'SIGNOUT_SUCCESS' })
});
}
}
authReducer.js
const initState = {
authError: null
}
const authReducer = (state = initState, action) => {
switch(action.type){
case 'LOGIN_ERROR':
console.log('login error');
return {
...state,
authError: 'Login failed'
}
case 'LOGIN_SUCCESS':
console.log('login success');
return {
...state,
authError: null
}
case 'SIGNOUT_SUCCESS':
console.log('signout success');
return state;
default:
return state
}
};
export default authReducer;
Home.js
import React, { Component } from 'react';
import firebase from 'firebase/app'
import 'firebase/firestore'
import 'firebase/auth'
import { Redirect } from 'react-router-dom'
import { signOut } from './../store/actions/authActions'
import { connect } from 'react-redux'
class Home extends Component {
render(){
console.log( "the props here in home.js", this.props)
return (
<div>
<h1> Welcome home</h1>
<button onClick={() => { firebase.auth().signOut();}}>Sign out!</button>
{/* <h1>Welcome {firebase.auth().currentUser.displayName}</h1> */}
{/* <img
alt="profile picture"
src={firebase.auth().currentUser.photoURL}
/> */}
</div>
);
}
}
const mapStateToProps = (state) => {
return{
auth: state.firebase.auth
}
}
const mapDispatchToProps = (dispatch) => {
return {
signOut: () => dispatch(signOut())
}
}
export default connect(mapStateToProps, mapDispatchToProps)(Home);
so in chrome developer tools when I am trying to print the props in console
it gives auth as {isLoaded: false, isEmpty: true}

Related

How to access redux store in private route?

I am trying to access auth state from my redux store in private route. I can get default state but cannot get updated state from store. I have stored my current user data and token in store. I can access these value from all other components except my private route component.
I have provided some code below
AdminRoute.js
import React from "react";
import { useSelector } from "react-redux";
import { Route, Redirect } from "react-router-dom";
const AdminRoute = ({ component: Component, ...rest }) => {
const authState = useSelector((state) => state.authState);
console.log(authState.currentUser);
return (
<Route
{...rest}
render={(props) =>
authState.currentUser?.id ? (
<Component {...props} />
) : (
<Redirect to="/auth" />
)
}
/>
);
};
export default AdminRoute;
Store.js
import { configureStore } from "#reduxjs/toolkit";
import { uiReducer } from "../slices/uiSlice";
import { authReducer } from "../features/auth/authSlice";
import { userReducer } from "../features/user/userSlice";
export default configureStore({
reducer: {
uiState: uiReducer,
authState: authReducer,
userState: userReducer,
},
});
authSlice.js
import { createSlice, createAsyncThunk } from "#reduxjs/toolkit";
import { apiUrl } from "../../api/apiConfig";
import Axios from "axios";
import { tokenConfig } from "../../utils/tokenConfig";
export const userLogin = createAsyncThunk(
"auth/userLogin",
async (userData, { rejectWithValue, dispatch }) => {
const { email, password } = userData;
try {
const { data } = await Axios.post(`${apiUrl}/auth/login`, {
email,
password,
});
if (data) {
localStorage.setItem("token", data.token);
return data;
}
} catch (err) {
if (!err.response) {
throw err;
}
return rejectWithValue(err.response.data?.msg);
}
}
);
export const getCurrentUser = createAsyncThunk(
"auth/getCurrentUser",
async (_, { rejectWithValue, getState }) => {
try {
const { data } = await Axios.get(
`${apiUrl}/user/cUser`,
tokenConfig(getState)
);
if (data) {
return data;
}
} catch (err) {
if (!err.response) {
throw err;
}
return rejectWithValue(err.response.data?.msg);
}
}
);
const authSlice = createSlice({
name: "auth",
initialState: {
token: localStorage.getItem("token"),
isLoggedIn: false,
currentUser: null,
},
extraReducers: {
[userLogin.pending]: (state, action) => {
state.status = "loading";
},
[userLogin.fulfilled]: (state, action) => {
state.status = "success";
state.isLoggedIn = true;
state.token = action.payload.token;
},
[userLogin.rejected]: (state, action) => {
state.status = "failed";
state.error = action.payload;
},
[getCurrentUser.pending]: (state, action) => {
state.status = "loading";
},
[getCurrentUser.fulfilled]: (state, action) => {
state.status = "success";
state.currentUser = action.payload;
state.isLoggedIn = true;
},
[getCurrentUser.rejected]: (state, action) => {
state.status = "failed";
state.error = action.payload;
},
},
});
const { actions: authActions, reducer: authReducer } = authSlice;
export { authActions, authReducer };
It seems like your protected route should be rerendered when the redux state updates. Perhaps you could remove some of the complexity.
import React from "react";
import { useSelector } from "react-redux";
import { Route, Redirect } from "react-router-dom";
const AdminRoute = (props) => {
const authState = useSelector((state) => state.authState);
return authState.currentUser?.id ? (
<Route {...props} />
) : (
<Redirect to="/auth" />
);
};
And just ensure you render the AdminRoute like any other regular Route component.
Ex:
<AdminRoute path="/protected" component={PrivateComponent} />
<AdminRoute
path="/protected"
render={props => <PrivateComponent {...props} />}
/>
<AdminRoute path="/protected">
<PrivateComponent />
</AdminRoute>

How to use React Redux Hooks to load spinners

I am trying to load spinner using react-redux hooks (useSelector and useDispatch). I am able to fetch data but not loader (in my case showLoader and hideLoader)
Expectation: when I click the refresh button I want to load spinner (in background it will refresh the data). Before clicking the button I am able to fetch data using useEffect hook.
//ActionCreators.js
export const EVENT_LOG = "EVENT_LOG";
export const EVENT_FAILURE = "EVENT_FAILURE";
export const SHOW_LOADER = "SHOW_LOADER";
export const HIDE_LOADER = "HIDE_LOADER";
//Actions.js
import {
EVENT_LOG,
EVENT_FAILURE,
SHOW_LOADER,
HIDE_LOADER,
} from "./actionCreators";
import { readList } from "./APIUtilsNew";
export const readLogs = (path) => {
return (dispatch) => {
readList(path)
.then((data) =>
dispatch(
{
type: EVENT_LOG,
payload: data,
},
console.log("EventLog Actions: ", data)
)
)
.catch((error) => {
dispatch({
type: EVENT_FAILURE,
payload: error,
});
throw error;
});
};
};
export const showLoader = () => (dispatch) => {
dispatch({
type: SHOW_LOADER,
});
};
export const hideLoader = () => (dispatch) => {
dispatch({
type: HIDE_LOADER,
});
};
//Reducers.js
import {
EVENT_LOG,
EVENT_FAILURE,
HIDE_LOADER,
SHOW_LOADER,
} from "../../actionCreators/index";
export const initialState = {
loading: false,
eventData: [],
eventError: false,
};
const eventReducer = (state = initialState, action) => {
switch (action.type) {
case EVENT_LOG:
return {
...state,
eventData: action.payload,
};
case EVENT_FAILURE:
return {
...state,
eventError: action.payload,
};
case HIDE_LOADER:
return {
...state,
loading: false,
};
case SHOW_LOADER:
return {
...state,
loading: true,
};
default:
return state;
}
};
export default eventReducer;
//React Component
import React, { useEffect } from "react";
import { useSelector, useDispatch } from "react-redux";
import { readLogs, showLoader, hideLoader } from "./eventActions";
import { FormattedMessage } from "react-intl";
import { XGrid } from "#material-ui/x-grid";
import { CSVLink } from "react-csv";
import IconBtn from "./IconBtn";
import MaterialTheme from "./MaterialTheme";
import { ThemeProvider as MuiThemeProvider } from "#material-ui/core/styles";
import Refresh from "./Refresh";
export default function EventsLog() {
const dispatch = useDispatch();
const eventLogs = useSelector(
(state) => state.eventReducer.eventData.data || []
);
const show = useSelector((state) => state.eventReducer.loading);
const hide = useSelector((state) => state.eventReducer.loading);
useEffect(() => {
dispatch(readLogs("/events"));
}, [dispatch]);
const update = () => {
dispatch(showLoader());
dispatch(hideLoader());
};
let rows = eventLogs.map((obj, index) => {
return (rows = {
id: index + 1,
Time: obj.time,
dateTime: obj.dateTime,
ID: obj.deviceId
});
});
const columns = [
{
field: "Time",
flex: 1,
type: "dateTime",
renderHeader: () => <FormattedMessage id={"time"} />
},
{
field: "dateTime",
flex: 1,
type: "dateTime",
renderHeader: () => <FormattedMessage id={"dateTime"} />
},
{
field: "ID",
flex: 1,
renderHeader: () => <FormattedMessage id={"id"} />
}
];
return (
<div>
<h1>
<FormattedMessage id="event.eventLog" />
<span>
<IconBtn iconLabel="refresh" />
</span>
<CSVLink data={rows} filename={"Log.csv"}>
<IconBtn iconLabel="cloud_download" onClick={update} />
</CSVLink>
</h1>
<div style={{ height: "90%", width: "100%" }}>
<MuiThemeProvider theme={MaterialTheme}>
<Refresh />
<XGrid
pageSize={50}
rowsPerPageOptions={[25, 50, 100]}
rows={rows}
columns={columns}
pagination={true}
hideFooterSelectedRowCount={true}
/>
</MuiThemeProvider>
</div>
</div>
);
}
This is the component where my spinner resides. I want to fetch this component while loading spinner
//Refresh Component
import React from "react";
export default function Refresh() {
return <div>Spinner....</div>;
}
I saw few examples online, where I found everything is in class components
// component Example
class FullPageLoader extends Component {
state = { }
render() {
const {loading} = this.props;
if(!loading) return null;
return (
<div class="loader-container">
<div className="loader">
<img src={LoaderGif} />
</div>
</div>
);
}
}
const mapStateToProps = state => ({ loading: state.application.loading })
export default connect(mapStateToProps)(FullPageLoader);
// Another Component
updateProfile = () =>{
this.props.dispatch( showLoader() )
Axios.post(`https://jsonplaceholder.typicode.com/users`, { user : { name : 'Test User' } })
.then(res => {
console.log( res );
this.props.dispatch( hideLoader() )
})
/* setTimeout(() => {
this.props.dispatch( hideLoader() )
}, 2000); */
}
<Button bsStyle="info" pullRight fill onClick={this.updateProfile} >
Update Profile
</Button>
Can somebody help me how to convert the above class to functional based component and instead of using mapStateToProps to hooks (or) please tell me how to load the spinner using react-redux hooks. I appreciate the help!
More easier way is to show and hide the loader in the action itself. Before the promise, setLoader as true. And in then and catch you can hide loader.
export const readLogs = (path) => {
return (dispatch) => {
showLoader();
readList(path)
.then((data) => {
hideLoader();
dispatch(
{
type: EVENT_LOG,
payload: data,
},
console.log("EventLog Actions: ", data)
)
})
.catch((error) => {
hideLoader();
dispatch({
type: EVENT_FAILURE,
payload: error,
});
throw error;
});
};
};
if it has to be done in the component itself, You can add a delay rather than calling them immediately. There doesn't seem to be any action that is happening here.
const update = () => {
dispatch(showLoader());
setTimeout(() => {
dispatch(hideLoader());
}, 1000);
};

Axios request failed?

i have get token from login with react redux, if i am try to authorized it with this token. the error is show Axios request failed: TypeError: Cannot read property 'token' of undefined i want to authorized it with token. the token is stored in localstorage but it can't authorized it when i am using (Token ${props.token} if i am trying this way (Token 5302f4340a76cd80a855286c6d9e0e48d2f519cb} then my AritcleList.js is Authorized it
here is the react-redux authentication
authAction.js
import axios from 'axios';
import * as actionTypes from './actionTypes';
export const authStart = () => {
return {
type: actionTypes.AUTH_START
}
}
export const authSuccess = token => {
return {
type: actionTypes.AUTH_SUCCESS,
token: token
}
}
export const authFail = error => {
return {
type: actionTypes.AUTH_FAIL,
error: error
}
}
export const logout = () => {
localStorage.removeItem('token');
return {
type: actionTypes.AUTH_LOGOUT
};
}
export const authLogin = (userData) => {
return dispatch => {
dispatch(authStart());
axios.post('http://localhost:8000/rest-auth/login/', userData)
.then(res => {
const token = res.data.key;
localStorage.setItem('token', token);
dispatch(authSuccess(token));
})
.catch(err => {
dispatch(authFail(err))
})
}
}
authReducer.js
import * as actionTypes from '../actions/actionTypes';
import { updateObject } from '../utility';
const initialState = {
isAuthenticated: null,
token: null,
error: null,
loading: false
}
const authStart = (state, action) => {
return updateObject(state, {
isAuthenticated: false,
error: null,
loading: true
});
}
const authSuccess = (state, action) => {
return updateObject(state, {
isAuthenticated: true,
token: action.token,
error: null,
loading: false
});
}
const authFail = (state, action) => {
return updateObject(state, {
error: action.error,
loading: false
});
}
const authLogout = (state, action) => {
return updateObject(state, {
token: null
});
}
export default function (state = initialState, action) {
switch (action.type) {
case actionTypes.AUTH_START: return authStart(state, action);
case actionTypes.AUTH_SUCCESS: return authSuccess(state, action);
case actionTypes.AUTH_FAIL: return authFail(state, action);
case actionTypes.AUTH_LOGOUT: return authLogout(state, action);
default:
return state;
}
}
articleList.js
import React, { useState, useEffect } from 'react';
import { Container, Row, Col } from 'react-bootstrap';
import Card from '../components/Card'
import FullPageLoader from "../components/FullPageLoader";
import axios from 'axios';
import { connect } from 'react-redux'
const NewsList = () => {
const [items, setItems] = useState([])
const [isLoading, setLoading] = useState(true)
const [isAuthenticated, setAuth] = useState(true); //i don't know how to authenticate it when i also login
useEffect((props) => {
const fetchItems = async () => {
try {
const config = {
headers: {
'Content-Type': 'application/json',
Authorization: `Token ${props.token}`
}
}
const res = await axios.get(`${process.env.REACT_APP_API_URL}/api/`, config);
setItems(res.data)
setLoading(false);
}
catch (err) {
console.log(`😱 Axios request failed: ${err}`);
}
}
fetchItems()
})
}, [items]);
return (
<Container className="mt-5">
< div className="bread-header" >
<h5>Dashboard</h5>
</div >
<hr />
<Row>
<Col sm={8}>
{
isLoading ? <FullPageLoader /> :
<div>
{itemData.map((item, index) => (
<Card key={index} item={item} isAuthenticated={isAuthenticated} ></Card>
))}
</div>
}
</Col>
</Row>
</Container >
)
}
const mapStateToProps = (state) => {
return {
isAuthenticated: state.auth.token,
}
}
export default connect(mapStateToProps)(NewsList)
Look at this thread: Sending the bearer token with axios
You need to add the token to the request as a header.

TypeError while fetching the user profile in Redux

error log image I have been facing this problem which is not working for me at the moment
I basically have an auth app that I am able to register and login however When I am trying to fetch the profile data I am facing a TypeError( Cannot read property 'FirstName' of undefined.
In the redux tool
the isAuthenticated: true
error: null
and profile: {
joined: xxxxxx
_id:4rt43dfdsletc
firstName: "xxxx"
email:"adfadf#fsa.com"
}
etc, everything is working and also the app includes the redux persist which is working also
However, in the Navbar, I am trying to display the user FirstName and I am getting the error
Here is my LOGIN.ACTION.JS
export const autUser = data => {
return async dispatch => {
// dispatch({ type: LOGIN_REQUEST}
return await apiLogin(data)
.then(res => {
const token = res.data.token;
console.log(token);
dispatch(success(token));
setAuthHeader(token);
dispatch(getUserProfile())
// console.log('User Details', jwt.decode(token));
})
//error will be dispatched here
.catch(err => console.log(err));
};
};
const success = token => {
localStorage.setItem(TOKEN_NAME, token);
return { type: LOGIN_SUCCESS };
};
const error = error => {
return { type: LOGIN_FAIL, payload: error };
};
FETCH PROFILE within the same file
export const getUserProfile = () => {
return async dispatch => {
try {
console.log("fetching profile......")
const { data : {user} } = await apiFetchProfile();
dispatch({ type: PROFILE_FETCHED, payload: user })
console.log(user)
} catch (e) {
console.error(e)
}
};
};
here is my index.js
store.dispatch(checkLoggedIn())
if(localStorage.donedeal){
setAuthHeader(localStorage.donedeal);
store.dispatch(getUserProfile())
}
ReactDOM.render(
<Provider store ={store}>
<App />
</Provider>
, document.getElementById('root'));
The Navbar.js
import React from "react";
import "./navbar.css";
import { connect } from "react-redux";
import { logOut} from "../../actions/login";
// import { Link } from "react-router-dom";
import logo from './logo.png'
const Navbar = ({ isAuth, logOut, profile}) => {
return (
<header>
<img src={logo} alt="Logo" className="logo" />
<nav className="nav_links">
<li><p> Buy and sell <span className="bold"> your things </span> </p></li>
<a className="cta" href=""><button> <li className="fas fa-plus"></li> Place ad </button></a>
{/* <li> Sign up</li> */}
{/* <li> Login</li> */}
{isAuth ? (
<div>
<p>{profile.firstName}</p>
<button onClick={() => logOut()}> Logout </button>
</div>
) : (<div><button> Login </button><button>Register</button></div>)
}
</nav>
</header>
);
};
const mapStateToProps = ({ login }) => {
return {
isAuth: login.isAuthenticated,
profile: login.profile
};
};
export default connect(
mapStateToProps,
{ logOut}
)(Navbar);
The above code is all over the place that's because I am just experimenting with it but it's registering and log in the user and even fetching the profile but I can't display the information.
There could a type or something that I have done wrong in which I cant see
Help would be very appreciated.
Here is the answer to the above problem(Code could be improve as well)
AuthAction
calls the apiLogin(axios)
then it returns the data
then we set the header
and we call the profileAction and we dispatch success and errors(not implemented yet)
export const signIn = request_data => {
console.log('Authenticating action is called ....................')
return async dispatch => {
try {
const {
data: { token }
} = await apiLogin(request_data);
setAuthHeader(token);
dispatch(getUserProfile());
dispatch(success(token));
} catch (e) {
const {
response: { data }
} = e;
dispatch(error(data.error));
}
};
};
getUserProfile
export const getUserProfile = () => {
return async dispatch => {
console.log('Fetching User profile....................')
try {
const {
data: { user }
} = await apiFetchProfile();
dispatch({ type: PROFILE_FETCHED, payload: user });
console.log(user)
} catch (e) {
console.error(e);
}
};
};
const success = token => {
localStorage.setItem(TOKEN_NAME, token);
return { type: AUTH_SUCCESS };
};
const error = error => {
return { type: AUTH_FAILED, payload: error };
};
authReducer.js
const INITIAL_STATE = {
isAuth: false,
profile: {},
error: null
};
export default (state = INITIAL_STATE, action) => {
switch (action.type) {
case AUTH_SUCCESS:
return { ...state, isAuth: true, error: null };
case AUTH_FAILED:
return {
...state,
isAuth: false,
error: action.payload
};
case USER_LOGGED_OUT:
return { ...state, isAuth: false, profile: {} };
case PROFILE_FETCHED:
return { ...state, profile: action.payload };
default:
return state;
}
};
export const checkToken = () => {
console.log('Checking LStorage is called ....................')
return dispatch => {
try {
const token = localStorage.getItem(TOKEN_NAME);
if (token === null || token === "undefined") {
return dispatch(error("You need to login "));
}
setAuthHeader(token);
dispatch(getUserProfile());
dispatch(success(token));
} catch (e) {
console.error(e);
}
};
};
index.js
import {checkToken} from './actions/auth_actions'
import store from './store'
// import setAuthHeader from './api/setAuthHeader'
// import jwt from 'jsonwebtoken';
store.dispatch(checkToken());
ReactDOM.render(
<Provider store ={store}>
<App />
</Provider>
, document.getElementById('root'));
These are the changes that I made and it working now
Now I have to handle errors
so basically, the SignIn actions call the backend API, it returns the token, then we send the authHeader and while doing that I call the getUserProfile and it calls the backend and gets the user profile
Then I created an action that will be called in the index.js at the start of the application and so that if the user reloads the page we dispatch the user profile again and that was the problem
Hope this helps somebody

Component not rerendering on a redux store change

Have a component to display user information. However, when the user logouts out, and shouldn't be in the store anymore ( I have set a dispatch up for this as well). Also, I am able to reload the entire page and then the user information displays. I have been having a go with componentDidUpdate and componentDidMount but I can't seem to figure it out.
Here is the view component:
// import React from "react";
// import { connect } from "react-redux";
// import { getUser } from "../store/actions/userActions";
// import { withRouter } from 'react-router-dom';
import React from 'react';
import { connect } from 'react-redux';
import * as actions from '../store/actions/auth';
class UserDetailView extends React.Component {
componentDidMount() {}
shouldComponentUpdate(nextProps, props) {
console.log(nextProps);
const username = this.props.user.username;
console.log(username);
if (username !== nextProps.username) {
console.log(username);
return true;
} else {
return false;
}
}
render() {
const user = this.props.user;
return (
<div>
{this.props.user ? (
<div>
<h3>{user.username}</h3>
{this.props.user.email}
</div>
) : (
<h3>Not Logged In</h3>
)}
</div>
);
}
}
const mapStateToProps = state => ({
username: state.username,
user: state.user
});
const mapStateToDispatch = dispatch => ({
onTryAutoSignup: () => dispatch(actions.authCheckState()),
getfetchUser: id => dispatch(actions.fetchUser(id))
});
export default connect(
mapStateToProps,
mapStateToDispatch
)(UserDetailView);
// class UserDetailView extends React.Component {
// componentDidMount() {
// const { getUser, userID } = this.props
// getUser(userID) //fixed
// }
// render() {
// console.log(this.props.userID)
// console.log(this.props.user)
// return (
// <ul>
// {this.props.user.map(user =>
// <li key={user.id}>{user.username}</li>
// )}
// </ul>
// );
// }
// }
// const mapStateToProps = (state, ownProps) => ({
// user: state.user,
// userID: ownProps.match.params.userID,
// });
// const mapDispatchToProps = dispatch => ({ //added
// getUser: (userID) => dispatch(getUser(userID))
// })
// export default withRouter(connect(mapStateToProps, {getUser})(UserDetailView)); //fixed
Reducer:
const getUserInformation = (state, action) => {
return Object.assign({}, state, {
user: action.payload.user
});
};
Action Generator and Action
export const authSuccess = (token, username) => {
return {
type: actionTypes.AUTH_SUCCESS,
token: token,
username: username
};
};
export const fetchUser = username => {
return dispatch => {
return axios
.get(`http://127.0.0.1:8000/api/user/${username}/`)
.then(res => {
const user = res.data;
dispatch(getUserInformation(user));
});
};
};
I see no reason to override shouldComponentUpdate, just inherit from React.PureComponent.
You have some mix-ups in action creators and reducers. It should be something like this:
dispatch(setUserInformation(user)); // dispatch action
const setUserInformation = ({ type: 'SET_USER_INFORMATION', user }); // this is the action creator, returns an object with the type and the payload
const reducer = (state, action) { // this is the reducer
switch (action.type) {
case 'SET_USER_INFORMATION':
return {
...state,
user: action.user
}
}
}

Resources