I have set up my very first Redux projet and I am trying to create a store for my current user by fetching it from my rails backend.
Although everything seems fine, this.props.user gives null in the component.
store.js:
import { createStore, applyMiddleware } from "redux";
import thunk from 'redux-thunk';
import rootReducer from "./reducers";
const store = createStore(
rootReducer,
applyMiddleware(thunk)
);
export default store;
actions.js
import { CREATE_USER, PROPAGATE_LOGIN, PROPAGATE_LOGOUT } from "./actionTypes";
import axios from 'axios';
export const getCurrentUser = () => {
return dispatch => {
axios.get("/users/get_current_user", {})
.then(response => {
if (response.data.user) {
dispatch(propagateLogin(response.data.user));
} else {
console.log("pas d'utilisateur connecté.")
dispatch(propagateLogout());
}
});
};
};
export const propagateLogin = (user) => ({
type: PROPAGATE_LOGIN,
payload: {
user
}
});
export const propagateLogout = () => ({
type: PROPAGATE_LOGOUT,
payload: { }
});
users.js reducer:
import { CREATE_USER, PROPAGATE_LOGIN, PROPAGATE_LOGOUT } from "../actionTypes";
const initialState = {
user: null
};
export default function(state = initialState, action) {
switch (action.type) {
case PROPAGATE_LOGIN: {
return {
user: action.payload.user
}
}
case PROPAGATE_LOGOUT: {
return {
user: null
}
}
default:
return state;
}
}
AppRouter.js (the connected component):
class AppRouter extends React.Component {
defaultState() {
return {
isReady: false,
user: this.props.user,
loginModalOpen: false,
signupModalOpen: false
}
}
constructor(props) {
super(props)
this.state = this.defaultState()
}
componentDidMount() {
this.getUser();
}
getUser(history = undefined) {
this.props.getCurrentUser();
this.setState({
isReady: true
});
}
render (){
// [...]
}
};
const mapStateToProps = (state /*, ownProps*/) => {
return {
user: state.users.user
}
}
const mapDispatchToProps = { getCurrentUser, propagateLogout }
export default connect(
mapStateToProps,
mapDispatchToProps
)(AppRouter);
And here is a screenshot from the React dev console: for the Provider Component:
