Why are my User.props always undefined? React-Native and Redux - javascript

I'm working with React-Native and Redux.
I need to access my User state on react redux after an action.
I try this with a simple console.log after the action on my Component (console.log(this.props.User)) but it is always undefined.
This is my Combine Reducer:
import { combineReducers } from 'redux'; import User from './userReducer';
export default combineReducers({
User });
This is my User Reducer:
import {
REGISTER_USER,
SIGNIN_USER } from '../types';
export default function(state=INITIAL_STATE, action){
switch(action.type){
case SIGNIN_USER:
return {
...state,
userData:{
uid: action.payload.localId || false,
token: action.payload.idToken || false,
refreshToken: action.payload.refreshToken || false,
}
};
break;
default:
return state
} }
This is my action:
export function signIn(data){
const request = axios({
method:'POST',
url:SIGNIN,
data:{
email: data.email,
password: data.password,
returnSecureToken:true
},
headers:{
"Content-Type":"application/json"
}
}).then(response => {
return response.data
}).catch( e=> {
console.log(e)
});
return {
type: SIGNIN_USER,
payload: request
}
}
Component where I try to get the state after action:
import { connect } from 'react-redux';
import { signIn } from '../Store/Actions/userActions';
import { bindActionCreators } from 'redux';
class LoginComponent extends React.Component {
state = {
email:'',
password:''
};
signInUser () {
try {
this.props.signIn(this.state).then( () => {
**console.log(this.props.User)**
})
} catch (error) {
console.log(error)
}
}
}
const mapStateToProps = (state) => {
return{
User: state.User
}
}
const mapDispatchToProps =( dispatch ) => {
return bindActionCreators({signIn}, dispatch)
}
export default connect(mapDispatchToProps,mapDispatchToProps)(LoginComponent);
The response on log just is: undefined
What is my mistake?? Thanks!

The order of the arguments that you are passing into connect method is wrong it expects mapStateToProps first and mapDispatchToProps as second
parameter. So your code has to be export default connect(mapStateToProps, mapDispatchToProps)(LoginComponent);
Here is the signature
connect([mapStateToProps], [mapDispatchToProps], [mergeProps], [options])

Related

Redux store returns null value in React class component

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:
As you write in user.js reducer user inital state is null
const initialState = {
user: null
};
Since get user action is async, you are just assining null value to user in inital state
defaultState() {
return {
isReady: false,
user: this.props.user, //this.props.user null here
loginModalOpen: false,
signupModalOpen: false
}
You can use this.props.user without assing it state value

React-Redux Action: 'Dispatch' is not a function

Still getting used to Redux, first off. I have a component that should simply load data for display when the component loads. I have redux setup with the store:
//store.js
import { createStore, applyMiddleware, compose } from 'redux';
import logger from 'redux-logger';
import thunk from 'redux-thunk';
import root from './reducers';
const middleware = [thunk, logger];
const initState = {};
const store = createStore(
root,
initState,
compose(
applyMiddleware(...middleware),
window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__()
)
);
export default store;
and all the reducers that I'll need in a full on combine reducers file:
//{projectFolder}/reducers/index.js
import { combineReducers } from 'redux';
import authReducer from './authReducer';
import errorsReducer from './errorReducer';
import suggestionReducer from './suggestionReducer';
import insiderReducer from './insiderReducer';
import connectionReducer from './connectionReducer';
import outsiderReducer from './outsiderReducer';
import contactReducer from './contactReducer';
import metaReducer from './metaReducer';
export default combineReducers({
auth: authReducer,
errors: errorsReducer,
suggestions: suggestionReducer,
insider: insiderReducer,
connection: connectionReducer,
outsider: outsiderReducer,
contact: contactReducer,
meta: metaReducer
});
The one that I'm interested in is the metaReducer which is the called by an action, or so it should be.
//metaReducer.js
import {GET_INSIDER_META_INFORMATION, GET_OUTSIDER_META_INFORMATION } from '../actions/types';
const initState = {
insider: {},
outsider: {}
};
export default (state = initState, { type, payload }) => {
switch (type) {
case GET_INSIDER_META_INFORMATION:
return{
...state,
insider: payload
}
case GET_OUTSIDER_META_INFORMATION:
return {
...state,
outsider: payload
}
default:
return state;
}
};
The meta reducer is just to house the information coming from the back-end and is each case of the reducer is called from the actions/meta.js file which looks like this:
//{projectfolder}/actions/meta.js
import {
GET_INSIDER_META_INFORMATION,
GET_OUTSIDER_META_INFORMATION,
POPULATE_ERRORS
} from "./types";
import Axios from "axios";
export const getMetaInsider = (dispatch) => {
return Axios.get("meta/insiders")
.then(res =>
dispatch({ type: GET_INSIDER_META_INFORMATION, payload: res.data })
)
.catch(err =>
dispatch({ type: POPULATE_ERRORS, payload: err.response.data })
);
};
export const getMetaOutsider = (dispatch) => {
return Axios.get("meta/outsiders")
.then(res => {
dispatch({ type: GET_OUTSIDER_META_INFORMATION, payload: res.data });
})
.catch(err =>
dispatch({ type: POPULATE_ERRORS, payload: err.response.data })
);
};
and My component that calls all of this is setup as below:
//{projectfolder}/components/home.js
import React, {Component} from 'react';
import {Card, CardTitle, CardSubtitle, CardBody} from 'reactstrap';
import { connect } from 'react-redux';
import PropTypes from 'prop-types';
import {getMetaInsider, getMetaOutsider} from '../actions/meta';
class Home extends Component{
constructor(props){
super(props);
this.state = {
insider:{},
outsider: {}
}
}
componentDidMount() {
console.log(this.props);
this.props.getMetaInsider();
this.props.getMetaOutsider();
}
render(){
let {insiders, outsiders} = this.state;
return(
<React.Fragment>
{*/ omitted as it's not really an issue right now, data is more important than layout /*}
</React.Fragment>
)
}
}
const mapState = state => {
console.log(state);
return {
insider: state.meta.insider,
outsider: state.meta.outsider
}
};
Home.propTypes = {
getMetaInsider: PropTypes.func.isRequired,
getMetaOutsider: PropTypes.func.isRequired,
insider: PropTypes.object.isRequired,
outsider: PropTypes.object.isRequired
};
export default connect(mapState, {getMetaInsider, getMetaOutsider})(Home);
So when the component loads, I get a horribly weird issue where it looks like jquery is being called, and it's imported in my App.js file for bootstrap. However, the main error is this:
"TypeError: dispatch is not a function
at http://localhost:3000/static/js/bundle.js:73524:22"
Which maps up to the .catch block of the getMetaInsider function.
You have to do something like this:
export const getMetaOutsider = () => {
return (dispatch) => {
Axios.get("meta/outsiders")
.then(res => {
dispatch({ type: GET_OUTSIDER_META_INFORMATION, payload: res.data });
})
.catch(err =>
dispatch({ type: POPULATE_ERRORS, payload: err.response.data })
);
}
};
Try this, It should work. Feedbacks are welcome.
redux-thunk handles functions passed as the argument to dispatch instead of objects.

Why is my props bringing back the action function, not the date?

I have a react app that is pulling down some data, It turns a promise so I am using Thunk. However when I log this.props, the getShift action prints out as a function.
The log returns:
{getShifts: ƒ}getShifts: ƒ ()proto: Object
Action:
import settings from '../../aws-config.js';
import Amplify, { Auth, API } from 'aws-amplify';
export const GET_STAFF_SHIFTS = 'get_staff_shifts';
export const SHIFTS_LOAD_FAIL = 'shifts_load_fail';
export const getShifts = () => dispatch => {
console.log('Fetching list of shifts for user...');
const request = API.get("StaffAPI", "/shifts", {
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
}
})
.then(response =>
dispatch({
type: 'GET_STAFF_SHIFTS',
payload: response
})
)
.catch(err =>
dispatch({type: 'SHIFTS_LOAD_FAIL'})
)
}
reducer:
import { getShifts, GET_STAFF_SHIFTS} from '../actions';
export default function(state = {}, action) {
switch(action.type){
case GET_STAFF_SHIFTS:
return Object.assign({}, state,{
start_time: action.payload
})
default:
return state;
}
}
Action:
import React, { Component } from 'react';
import Amplify, { Auth, API } from 'aws-amplify';
import {connect} from 'react-redux';
import {bindActionCreators} from 'redux';
import {getShifts} from '../actions/index';
import settings from '../../aws-config.js';
Amplify.configure(settings);
class StaffRota extends Component {
componentWillMount() {
this.props.getShifts();
}
renderPosts(){
console.log(this.props);
return (
<div></div>
);
}
}
function MapDispatchToProps(dispatch) {
return bindActionCreators({ getShifts }, dispatch);
}
export default connect(null, MapDispatchToProps)(StaffRota);
The action creator is supposed to be a function, which is expected. So console logging this.props.getShifts will give you a function.
There are two issues here:
first thing you are dispatching the wrong action type
dispatch({type: 'GET_STAFF_SHIFTS', ... }) instead of dispatch({type: GET_STAFF_SHIFTS, ... }) which you are expecting in your reducer.
secondly you ought to use the redux state via a mapStateToProps function
function MapDispatchToProps(dispatch) {
return bindActionCreators({ getShifts }, dispatch);
}
function MapStateToProps(state) {
return {
shift: state.start_time OR state.your_reducer.start_time
}
}
export default connect(MapStateToProps, MapDispatchToProps)(StaffRota);
And use this state (that is mapped to prop) via this.props.shift.

Multi Api call using redux and thunk doesn't work properly

I want to use redux to call API in react native. Redux is ok when I want to call only single API in a component but when I want to dispatch more than one API. it just mix up and i can not handle in componentWillRecieveProps.
this is my component which I want to call API in it:
import React, { Component } from 'react';
import { Alert,View,Text,Button } from 'react-native';
import { connect } from 'react-redux';
import { push } from 'react-router-redux';
import { generateOTP,getAnother } from '../Actions'
class Splash extends Component {
constructor(props) {
super(props);
this.onPress=this.onPress.bind(this);
this.onClick=this.onClick.bind(this);
}
componentWillReceiveProps(nextProps) {
if (nextProps !== this.props) {
if( nextProps.api.status === 'api_success' && nextProps.api.error===null) {
Alert.alert("yes successfully take data");
}
if(nextProps.myApp.status === 'success' && nextProps.myApp.error === null){
Alert.alert("you call second api");
}
}
}
onClick(){
this.props.dispatch(getAnother());
}
onPress(){
this.props.dispatch(generateOTP());
}
render() {
return (
<View>
<Button title="Click me first" onPress={this.onPress}/>
<Text>Extraa space</Text>
<Text>Extraa space</Text>
<Button title="Click me" onPress={this.onClick}/>
</View>
);
}
}
export default connect(state => state)(Splash)
To tell you exactly when i click on Click me button both condition inside this if (nextProps !== this.props) block will be true and trigger Alert to me.
api-reducer.js:
const initialState = {
data: {},
error: null,
status: null
};
export default function reducer(state = initialState, action) {
switch (action.type) {
case "GENERATE_OTP_PENDING":
// Action is pending (request is in progress)
return {...state, status: 'fetching'}
case "GENERATE_OTP_FULFILLED":
// Action is fulfilled (request is successful/promise resolved)
return {
...state,
error: null,
data: action.payload.data,
status: 'api_success'
}
case "GENERATE_OTP_REJECTED":
// Action is rejected (request failed/promise rejected)
return {
...state,
error: action.payload,
status: 'api_error'
}
default:
return state;
}
};
tagreducer.js:
const initialState = {
data: {},
error: null,
status: null
};
export default function reducer(state = initialState, action) {
switch (action.type) {
case "GET_INFORMATION_PENDING":
// Action is pending (request is in progress)
return {...state, status: 'fetching'}
case "GET_INFORMATION_FULFILLED":
// Action is fulfilled (request is successful/promise resolved)
return {
...state,
error: null,
data: action.payload.data,
status: 'success'
}
case "GET_INFORMATION_REJECTED":
// Action is rejected (request failed/promise rejected)
return {
...state,
error: action.payload,
status: 'error'
}
default:
return state;
}
};
this is the way I index or combine both recuder:
import { combineReducers } from 'redux';
import { routerReducer } from 'react-router-redux';
import api from './api-reducer';
import myApp from './tagreducer';
export default combineReducers({
api,
myApp,
routing: routerReducer,
});
The Actions.js:
import axios from 'axios';
import * as config from '../Config';
export const generateOTP = () => ({
type: 'GENERATE_OTP',
payload: axios({
method: 'get',
url: 'https://jsonplaceholder.typicode.com/posts',
headers: {"Accept": "application/json"}
})
});
export const getAnother = () => ({
type: 'GET_INFORMATION',
payload: axios({
method: 'get',
url: 'https://newsapi.org/v2/sources?apiKey=94da7332cf0a4b1ea685afc9a6829078',
headers: {"Accept": "application/json"}
})
});
and finally my Store.js:
import { applyMiddleware, createStore } from 'redux';
import { routerMiddleware } from 'react-router-redux';
import thunk from 'redux-thunk';
import promiseMiddleware from 'redux-promise-middleware';
import logger from 'redux-logger'
import reducers from './Reducers';
export default function configureStore(history) {
const middleware = applyMiddleware(
promiseMiddleware(),
thunk,
logger,
routerMiddleware(history));
return createStore(reducers, {}, middleware);
}

React + Redux binded state has no data

After one of the Redux tutorials decided to implement that facny action->reducer->store->view chain for simple app with only login part.
Seems like all setted up but when I run my app - in mapStateToProps(currentState) no any sign of the any custom state fields which I expected to see! (default state from reducer). But the action function is fine, as you can see on the screenshot
I can't see whats wrong here so, decided to ask it.
So here is the code
So, first of all - store.js
import { createStore, applyMiddleware } from 'redux';
import rootReducer from '../reducers';
import thunk from 'redux-thunk';
export default function configureStore(initialState) {
const store = createStore(rootReducer, initialState, applyMiddleware(thunk));
if (module.hot) {
module.hot.accept('../reducers', () => {
const nextRootReducer = require('../reducers');
store.replaceReducer(nextRootReducer);
});
}
return store;
}
then login reducer
const initialState = {
user: {
name: '',
password: ''
},
fetching: false
}
export default function login(state = initialState, action) {
switch (action.type) {
case LOGIN_REQUEST: {
return { ...state, fetching: true }
}
case LOGIN_SUCCESS: {
return { ...state, user: action.data, fetching: false }
}
case LOGIN_FAIL: {
return { ...state, user: -1, fetching: false }
}
default: {
return state;
}
}
}
and the root (reducers/index.js):
import login from './login/login';
import { combineReducers } from 'redux'
export default combineReducers({
login
});
the action
import {
LOGIN_REQUEST,
LOGIN_SUCCESS,
LOGIN_FAIL
} from '../../constants/login.js';
export function onLoginAttempt(userData) {
return (dispatch) => {
dispatch({
type: LOGIN_REQUEST,
user: userData
})
tryLogin(userData);
}
};
function tryLogin(userData) {
let url = 'SignIn/Login ';
return (dispatch) => {
axios.post(url, userData)
.then((response) => dispatch({
type: LOGIN_SUCCESS,
data: response.data
})).error((response) => dispatch({
type: LOGIN_FAIL,
error: response.error
}))
}
};
So here is entrance point:
import React from 'react';
import ReactDOM from 'react-dom';
import { createStore } from 'redux';
import { Provider } from 'react-redux';
import App from './containers/app.js';
import configureStore from './store/configureStore';
let store = createStore(configureStore);
ReactDOM.render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById("content")
);
and here is the app.js (Login is just sompe custom div with two fields nothing special)
import React, { Component } from 'react';
import { bindActionCreators } from 'redux'
import { connect } from 'react-redux';
import Login from '../components/login/Login';
import * as pageActions from '../actions/login/login'
class App extends Component {
render() {
const { user, fetching } = this.props;
const { onLoginAttempt } = this.props.pageActions;
return <div>
<Login name={user.name} password={user.password} fetching={fetching} onLoginAttempt={onLoginAttempt} />
</div>
}
}
function mapStateToProps(currentState) {
return {
user: currentState.user,
fetching: currentState.fetching
}
}
function mapDispatchToProps(dispatch) {
return {
pageActions: bindActionCreators(pageActions, dispatch)
}
}
export default connect(mapStateToProps, mapDispatchToProps)(App)
I see that you have state which looks like:
reduxState = {
login: {
user: {
name: '',
password: ''
},
fetching: false
}
}
but then you try to access properties that don't exist.
function mapStateToProps(currentState) {
return {
user: currentState.user,
fetching: currentState.fetching
}
}
I think you need to:
function mapStateToProps(currentState) {
return {
user: currentState.login.user,
fetching: currentState.login.fetching
}
}
You have this line let store = createStore(configureStore); on your entry point. However, inside configureStore, you have a call to createStore()
Basically you're calling something like createStore(createStore(reducers)). That's probably the cause of the problem.
You should probably call it like
let store = configureStore( /* pass the initial state */ )

Categories