react-redux: Cannot read property 'isLogin' of undefined - javascript

I use JWT token authentication for auth.
When I access to localhost:4000/api/refresh with token, it verify if token is expired, and return refreshed token with status code 200.
And middleware detect if token is valid and return to 200 or 401.
Backend is works perfectly. But frontend got some errors.
I use redux for global state manage.
Here is my codes.
[reducers.js]
// Actions
const LOGIN_TRUE = 'LOGIN_TRUE';
const LOGIN_FALSE = 'LOGIN_FALSE';
const CHECK_TOKEN = 'CHECK_TOKEN';
const REFRESH_TOKEN = 'REFRESH_TOKEN';
// Action Creators
function loginTrue() {
return {
type: LOGIN_TRUE
}
}
function loginFalse() {
return {
type: LOGIN_FALSE
}
}
function checkToken() {
return {
type: CHECK_TOKEN
}
}
function refreshToken() {
return {
type: REFRESH_TOKEN
}
}
// Reducer
const initialState = {
isLogin: false
}
function reducer(state = initialState, action) {
switch(action.type) {
case LOGIN_TRUE:
return applyLoginTrue(state, action);
case LOGIN_FALSE:
return applyLoginFalse(state, action);
case CHECK_TOKEN:
return applyCheckToken(state, action);
case REFRESH_TOKEN:
return applyRefreshToken(state, action);
default:
return state;
}
}
// Reducer Functions
function applyLoginTrue(state) {
return {
...state,
isLogin: true
}
}
function applyLoginFalse(state) {
return {
...state,
isLogin: false
}
}
function applyCheckToken(state) {
const token = localStorage.getItem('token');
if(token !== null) {
return {
...state,
isLogin: true
}
} else {
return {
...state,
isLogin: false
}
}
}
function applyRefreshToken(state) {
console.log(state);
const token = localStorage.getItem('token');
if(token !== null) {
fetch("http://localhost:4000/api/refresh", {
method: "POST",
headers: {
'Authorization':`JWT ${token}`
}
})
.then(res => {
if(res.status === 200) {
return res.json();
} else {
console.log("applyRefreshToken() res.status is not 200");
}
})
.then(json => {
localStorage.clear();
localStorage.setItem('token', json.token);
return {
...state,
isLogin: true
}
})
} else {
console.log("applyRefreshToken() token is null");
return {
...state,
isLogin: false
}
}
}
// Export Action Creators
export const actionCreators = {
loginTrue,
loginFalse,
checkToken,
refreshToken
};
// Export Reducer
export default reducer;
After wrote the reducer.js, I made dummy component to test it.
componentDidMount() {
const { refreshToken } = this.props;
refreshToken();
}
render () {
const { isLogin } = this.props;
return (
<div className="wrap">
{ isLogin ? "Under Construction" : "Login please" }
</div>
)
}
export default connect(mapStateToProps, mapDispatchToProps)(index);
But it throw errors like this -> TypeError: Cannot read property 'isLogin' of undefined
I can't find where is the error occured.
Because loginTrue(), loginFalse(), checkToken() works perfectly.
Is there any solution about this?
Thanks.
[mapStateToProps.js]
const mapStateToProps = (state) => {
const { isLogin } = state;
return {
isLogin
}
}
export default mapStateToProps;
[mapDispatchToProps.js]
import { bindActionCreators } from 'redux';
import { actionCreators } from './reducer';
const mapDispatchToProps = (dispatch) => {
return {
loginTrue: bindActionCreators(actionCreators.loginTrue, dispatch),
loginFalse: bindActionCreators(actionCreators.loginFalse, dispatch),
checkToken: bindActionCreators(actionCreators.checkToken, dispatch),
refreshToken: bindActionCreators(actionCreators.refreshToken, dispatch)
}
}
export default mapDispatchToProps;

applyRefreshToken is async, and therefore returns undefined.
So when your reducer executes:
case REFRESH_TOKEN:
return applyRefreshToken(state, action);
You actually set your state to undefined which eventually sets this.props to undefined and hence the error.
Either run the async logic and dispatch the new state after getting the response or use thunk / saga / any other middleware which will enable you to have async action creators.

Related

Why the react component is not returning the current data from redux?

I have a react app that is connected with redux. The component has a form that makes a PUT call to the api when the form is submitted. When I submit the form, I can see that redux gets updated accordingly but when I try to access the redux state as a prop in my component, the props data does not return the current data and is off by 1. For example, here's the data in my redux store:
Redux store:
When I do console.log("THIS PROPS: ", this.props) in my component, I see that it accountError is showing up as null
When I dispatch the action again the second time, only then I see that I am getting the data from redux in my props:
Here is the code that I have currently:
OrgAccount.js
import { registerOrgAccount, getListOfOrgsAndAccts } from "../../store/actions";
handleSubmit = () => {
this.props.registerOrgAccount(this.state)
console.log("THIS PROPS: ", this.props)
if(this.props.accountError === null) {
this.toggleTab(this.state.activeTab + 1);
}
};
<Link
to="#"
className="btn w-lg"
onClick={() => {
if (this.state.activeTab === 1) {
this.handleSubmit();
}
}}
>
Next
</Link>
const mapStatetoProps = (state) => {
const { accounts, accountError, loading } = state.OrgAccount;
return { accounts, accountError, loading };
};
const mapDispatchToProps = (dispatch) => {
return {
getListOfOrgsAndAccts: () => {
dispatch(getListOfOrgsAndAccts())
},
registerOrgAccount: (data) => {
dispatch(registerOrgAccount(data))
},
}
}
export default connect(mapStatetoProps, mapDispatchToProps)(OrgAccount);
Reducer:
const initialState = {
accountError: null, accountsError: null, message: null, loading: null
}
const orgAccount = (state = initialState, action) => {
switch (action.type) {
case REGISTER_ORG_ACCOUNT:
state = {
...state,
account: null,
loading: true,
// accountError: null
}
break;
case REGISTER_ORG_ACCOUNT_SUCCESSFUL:
state = {
...state,
account: action.payload,
loading: false,
accountError: null
}
break;
case REGISTER_ORG_ACCOUNT_FAILED:
state = {
...state,
loading: false,
accountError: action.payload ? action.payload.response : null
}
break;
...
default:
state = { ...state };
break;
}
return state;
}
export default orgAccount;
Action
export const registerOrgAccount = (account) => {
return {
type: REGISTER_ORG_ACCOUNT,
payload: { account }
}
}
export const registerOrgAccountSuccessful = (account) => {
return {
type: REGISTER_ORG_ACCOUNT_SUCCESSFUL,
payload: account
}
}
export const registerOrgAccountFailed = (error) => {
return {
type: REGISTER_ORG_ACCOUNT_FAILED,
payload: error
}
}
Saga.js
import { registerOrgAccountSuccessful, registerOrgAccountFailed, getListOfOrgsAndAcctsSuccessful, getListOfOrgsAndAcctsFailed } from './actions';
import { putOrgAccount } from '../../../helpers/auth_helper';
function* registerOrgAccount({ payload: { account } }) {
try {
const response = yield call(putOrgAccount, {
orgId: account.orgId,
accountNumber: account.accountNumber,
accountName: account.accountName,
accountCode: account.accountCode,
urlLink: account.urlLink,
location: account.location,
accountType: account.accountType,
address: account.address,
city: account.city,
state: account.state,
zip: account.zip,
country: account.country,
email: account.email,
eula: "blah"
});
yield put(registerOrgAccountSuccessful(response));
} catch (error) {
yield put(registerOrgAccountFailed(error));
}
}
To understand the root cause here, I think it helps to know a little about immutability and how React rerenders. In short, React will rerender when it detects reference changes. This is why mutating a prop, wont trigger a rerender.
With that in mind, at the time you call handleSubmit, this.props.accountError is simply a reference to a value somewhere in memory. When you dispatch your action and your state is updated, a new reference will be created, which will trigger a rerender of your component. However the handleSubmit function that was passed to your element still references the old this.props.accountError, which is why it is still null.
You could get around this by implementing your check in the componentDidUpdate lifecycle method. E.g. something like this:
componentDidUpdate(prevProps) {
if (prevProps.accountError === null && this.props.accountError !== null) {
this.toggleTab(this.state.activeTab + 1)
}
}

How can I avoid slow get state from the Redux store?

I have App contains Tabs that gets data from API bassed on token I passed to the header request,
So in the login screen, i dispatch an action to save token after user login and it's saved well
But the issue is after user login and go to home screen "save token Action dispatched" I got error 401 unauthorized, and when I log Token in getting data function I got empty in the debugger although save token dispatched".
But when I open the app again after killing App and Go to Home " because I'm login before and save token, And I use redux-persist to save it so it's saved before when logging first time" its work fine!
So I don't know whats the wrong When Login at first time!
here's Home Screen Code snippet
constructor(props) {
super(props);
this.state = {
token: this.props.token,
}
}
// Get all playList user created
getAllPlayLists = async () => {
const {token} = this.state;
console.log(token); // After first time I login I got here empty, But after i kill the app or re-open it i got the token well :)
let AuthStr = `Bearer ${token}`;
const headers = {
'Content-Type': 'application/json',
Authorization: AuthStr,
};
let response = await API.get('/my_play_list', {headers: headers});
let {
data: {
data: {data},
},
} = response;
this.setState({playlists: data});
};
componentDidMount() {
this.getAllPlayLists();
}
const mapStateToProps = state => {
console.log('is??', state.token.token); here's i got the token :\\
return {
token: state.token.token,
};
};
export default connect(mapStateToProps)(Home);
Redux stuff
reducers
import {SAVE_TOKEN} from '../actions/types';
let initial_state = {
token: '',
};
const saveTokenReducer = (state = initial_state, action) => {
const {payload, type} = action;
switch (type) {
case SAVE_TOKEN:
state = {
...state,
token: payload,
};
break;
}
return state;
};
export default saveTokenReducer;
--
import {IS_LOGIN} from '../actions/types';
let initialState = {
isLogin: false,
};
const userReducer = (state = initialState, action) => {
switch (action.type) {
case IS_LOGIN:
state = {
...state,
isLogin: true,
};
break;
default:
return state;
}
return state;
};
export default userReducer;
actions
import {SAVE_TOKEN} from './types';
export const saveToken = token => {
return {
type: SAVE_TOKEN,
payload: token,
};
};
-
import {IS_LOGIN} from './types';
export const isLoginFunc = isLogin => {
return {
type: IS_LOGIN,
payload: isLogin,
};
};
store
const persistConfig = {
key: 'root',
storage: AsyncStorage,
};
const rootReducer = combineReducers({
user: userReducer,
count: countPlayReducer,
favorite: isFavoriteReducer,
token: saveTokenReducer,
});
const persistedReducer = persistReducer(persistConfig, rootReducer);
Edit
I figure out the problem, Now in the Login function after getting the response from the API I dispatch two actions Respectively
facebookAuth = async()=>{
....
this.props.dispatch(isLoginFunc(true)); // first
this.props.dispatch(saveToken(token)); // second
....
}
But when I dispatch saveToken(token) firstly I can see the token in the debugger without problems!
So how can i handle it and dispatch two actions at the same time?
When response token get then redirect to page. Maybe should add callback function for action. For example:
This following code is for add record
addVideoGetAction(values, this.props.data, this.callBackFunction)
This callBackFunction is close the modal
callBackFunction = (value: any) => {
this.setCloseModal();
};
You will use callback function in login action. This function will redirect to the page
This function call in saga. this following code
function* setAddOrUpdate(params: any) {
params.callback(redirectPageParams);
}
In redux we should NEVER alter the state object in reducer ... we return a brand new object
const saveTokenReducer = (state = initial_state, action) => {
const {payload, type} = action;
switch (type) {
case SAVE_TOKEN:
state = {
...state,
token: payload,
};
break;
}
return state;
};
Instead
const saveTokenReducer = (state = initial_state, action) => {
const { payload, type } = action;
switch (type) {
case SAVE_TOKEN:
return { ...state, token: payload };
default:
return state;
}
};
Regarding dispatching two actions at the same time
const userReducer = (state = initial_state, { action, type }) => {
switch (type) {
case UPDATE_LOGIN:
return { ...state, token: payload, isLogin: !!payload };
default:
return state;
}
};
-
facebookAuth = async () => {
this.props.dispatch(updateLogin(token));
};
-
import { UPDATE_LOGIN } from './types';
export const updateLogin = token => {
return {
type: UPDATE_LOGIN,
payload: token,
};
};

Redux Saga not triggered/api not called - props undefined

I'm learning redux-saga and having a problem with calling my api.
It seems like my saga is not triggered and my props stay undefined.
I'm using fake-server for mocking data.
I tested the server and it seems to be working fine outside the saga.
My code looks like this:
UserView.js
const UserView = (props) => {
const {user} = props;
return (
<Header as='h2'>{user.name}</Header>
);
}
export default UserView
actions.js
export function showUserRequest(){
return{
type: USER_REQUEST
}
}
export function showUserSuccess(user) {
return {
type: USER_SUCCESS,
payload: user
}
}
export function showUserError(error){
return{
type: USER_ERROR,
payload: error
}
}
reducer.js
export default function (state = initialState, action) {
switch(action.type){
case USER_REQUEST:
return{
...state,
requesting: true,
successful: false,
errors: []
}
case USER_SUCCESS:
return{
...state,
user: action.payload,
requesting: false,
successful: true,
errors: [],
}
case USER_ERROR:
return{
requesting: false,
successful: false,
errors: state.errors.concat[{
body: action.error.toString(),
time: new Date(),
}],
}
default:
return state;
}
}
user.js
class User extends Component {
constructor(props) {
super(props);
this.fetchUser = this.fetchUser.bind(this);
}
componentWillMount(){
this.fetchUser();
}
fetchUser(){
const { showUserRequest } = this.props;
return showUserRequest;
}
render() {
const user = this.props;
return (<UserView user = {user.user}/>);
}
}
function mapStateToProps(state) {
return {
user: state.user
};
}
export default connect(mapStateToProps, {showUserRequest})(User);
sagas.js
const api = 'http://localhost:8080/user';
function userRequestApi () {
return axios.get(api)
}
function* userRequestFlow() { //does not seem to get invoked
try {
const user = yield call(userRequestApi);
yield put(showUserSuccess(user))
} catch (error) {
yield put(showUserError(error))
}
}
function* userWatcher() { //seems to get invoked
yield takeLatest(USER_REQUEST, userRequestFlow);
}
export default userWatcher
indexSaga.js/indexReducer.js
export default function* IndexSaga() {
yield all([
SignupSaga(),
LoginSaga(),
UserSaga()
]);
}
const IndexReducer = combineReducers({
route: routerReducer,
form: formReducer,
user: userReducer
})
export default IndexReducer
It seems like the userRequestFlow function is not called at all.
I'm sure it's just a silly rookie mistake but I just can't figure it out.
What am I doing wrong?
In your user.js you need to define mapDispatchToProps() and dispatch the showUserRequest action like this:
function mapDispatchToProps(dispatch) {
return {
dispatchUserRequest: () => dispatch(showUserRequest()),
};
}
export default connect(mapStateToProps, mapDispatchToProps)(User);
And then invoke this.props.dispatchUserRequest() when you wish to dispatch the action.

Why does mapping state to props give undefined?

I'm having a problem with my setup of Redux. I didn't have a problem with single file of posts actions and reducers, but as soon as added a searchQueries sections, it shows only undefined values for the searchQueries props.
I've tried copying it as far as I can and modifying it for the second set of actions/reducers, but I'm still ending up with undefined props in the case of searchQueries. I'm getting all the props, including the default values in the case of posts. Here's the code for each of these:
/actions/posts.js:
import axios from 'axios'
export function postsHasErrored(bool) {
return {
type: 'POSTS_HAS_ERRORED',
hasErrored: bool
}
}
export function postsIsLoading(bool) {
return {
type: 'POSTS_IS_LOADING',
isLoading: bool
}
}
export function postsFetchDataSuccess(posts) {
return {
type: 'POSTS_FETCH_DATA_SUCCESS',
posts
}
}
export function totalPagesFetchDataSuccess(totalPages) {
return {
type: 'TOTAL_PAGES_FETCH_DATA_SUCCESS',
totalPages
}
}
export function postsFetchData(url) {
return (dispatch) => {
dispatch(postsIsLoading(true))
axios.get(url)
.then(res => {
if (res.status !== 200) throw Error(res.statusText)
dispatch(postsIsLoading(false))
return res
})
.then(res => {
dispatch(postsFetchDataSuccess(res.data))
dispatch(totalPagesFetchDataSuccess(res.headers['x-wp-totalpages']))
})
.catch(() => dispatch(postsHasErrored(true)))
}
}
/actions/searchQueries.js:
const readLocation = (name) => {
let parameter = getParameterByName(name);
if (name === 'categories') {
if (parameter) {
parameter = parameter.split(',')
for (let i = 0; i < parameter.length; i++) parameter[i] = parseInt(parameter[i], 10)
}
else parameter = []
}
if (parameter === null) {
if (name === 'search') parameter = ''
if (name === 'page') parameter = 1
}
console.log(parameter)
return parameter
}
export function setSearchString(searchString) {
return {
type: 'SET_SEARCH_STRING',
searchString
}
}
export function setSearchCategories(searchCategories) {
return {
type: 'SET_SEARCH_CATEGORIES',
searchCategories
}
}
export function setSearchPage(searchPage) {
return {
type: 'SET_SEARCH_PAGE',
searchPage
}
}
export function searchQueriesSetting() {
return (dispatch) => {
dispatch(setSearchString(readLocation('search')))
dispatch(setSearchCategories(readLocation('categories')))
dispatch(setSearchPage(readLocation('page')))
}
}
/reducers/posts.js:
export function postsHasErrored(state = false, action) {
switch (action.type) {
case 'POSTS_HAS_ERRORED':
return action.hasErrored
default:
return state
}
}
export function postsIsLoading(state = false, action) {
switch (action.type) {
case 'POSTS_IS_LOADING':
return action.isLoading
default:
return state
}
}
export function posts(state = [], action) {
switch (action.type) {
case 'POSTS_FETCH_DATA_SUCCESS':
return action.posts
default:
return state
}
}
export function totalPages(state = 1, action) {
switch (action.type) {
case 'TOTAL_PAGES_FETCH_DATA_SUCCESS':
return parseInt(action.totalPages, 10)
default:
return state
}
}
/reducers/searchQueries.js:
export function searchString(state = '', action) {
switch (action.type) {
case 'SET_SEARCH_STRING':
return action.searchString
default:
return state
}
}
export function searchCategories(state = [], action) {
switch (action.type) {
case 'SET_SEARCH_CATEGORIES':
return action.searchCategories
default:
return state
}
}
export function searchPage(state = 1, action) {
switch (action.type) {
case 'SET_SEARCH_PAGE':
return action.searchPage
default:
return state
}
}
/reducers/index.js:
import { combineReducers } from 'redux'
import { posts, totalPages, postsHasErrored, postsIsLoading } from './posts'
import { searchString, searchCategories, searchPage } from './searchQueries'
export default combineReducers({
posts,
postsHasErrored,
postsIsLoading,
totalPages,
searchString,
searchCategories,
searchPage
})
/components/PostsList.js
// dependencies
import React, { Component } from 'react'
import axios from 'axios'
import { connect } from 'react-redux'
// components
import PostsListItem from './PostsListItem'
import PostsPages from './PostsPages'
// actions
import { postsFetchData } from '../actions/posts'
import { searchQueriesSetting } from '../actions/searchQueries'
// styles
import '../styles/css/postsList.css'
// shared modules
import { createSearchUrl } from '../sharedModules/sharedModules'
class PostsList extends Component {
componentWillReceiveProps(nextProps) {
if (nextProps.searchPage !== this.props.searchPage) this.componentDidMount()
}
componentDidMount() {
this.props.searchQueriesSetting()
this.props.fetchData(createSearchUrl(
'http://localhost/wordpress-api/wp-json/wp/v2/posts?per_page=1',
this.props.searchCategories,
this.props.searchString,
this.props.searchPage
))
}
render() {
console.log(this.props)
const { isLoading, hasErrored, posts } = this.props
if (isLoading) return <div className='posts-list'><h2 className='loading'>Loading...</h2></div>
const postsList = posts.map(post => <PostsListItem post={post} key={post.id} />)
return (
<div className='posts-list'>
{postsList}
<PostsPages />
</div>
)
}
}
const mapStateToProps = (state) => {
return {
posts: state.posts,
hasErrored: state.postsHasErrored,
isLoading: state.postsIsLoading,
searchCategories: state.searchCategories,
searchString: state.searchString,
searchPage: state.searchPage
}
}
const mapDispatchToProps = (dispatch) => {
return {
fetchData: (url) => dispatch(postsFetchData(url)),
searchQueriesSetting: () => dispatch(searchQueriesSetting())
}
}
export default connect(mapStateToProps, mapDispatchToProps)(PostsList)
/components/PostsPages.js
// dependencies
import React, { Component } from 'react'
import { Link } from 'react-router-dom'
import { connect } from 'react-redux'
// actions
import { setSearchPage } from '../actions/searchQueries'
// shared modules
import { createSearchUrl } from '../sharedModules/sharedModules'
class PostsPages extends Component {
isLinkEdgy = (pageNumber) => {
if (parseInt(pageNumber, 10) <= 1) return ''
if (parseInt(pageNumber, 10) >= parseInt(this.props.totalPages, 10)) return this.props.totalPages
return pageNumber
}
render() {
const { totalPages, currentPage, searchCategories, searchString, setSearchPage } = this.props
const previousUrl = createSearchUrl('/blog', searchCategories, searchString, this.isLinkEdgy(parseInt(currentPage, 10) - 1))
const nextUrl = createSearchUrl('/blog', searchCategories, searchString, this.isLinkEdgy(parseInt(currentPage, 10) + 1))
return (
<div className='posts-pages'>
<ul className='posts-pages-list'>
<li><Link to={previousUrl} onClick={() => setSearchPage(this.isLinkEdgy(parseInt(currentPage, 10) - 1))}>Prev page</Link></li>
<li><Link to={nextUrl} onClick={() => setSearchPage(this.isLinkEdgy(parseInt(currentPage, 10) + 1))}>Next page</Link></li>
</ul>
</div>
)
}
}
const mapStateToProps = (state) => {
return {
totalPages: state.totalPages,
currentPage: state.searchPage,
searchCategories: state.searchCategories,
searchString: state.searchString
}
}
const mapDispatchToProps = (dispatch) => {
return {
setSearchPage: (searchPage) => dispatch(setSearchPage(searchPage))
}
}
export default connect(mapStateToProps, mapDispatchToProps)(PostsPages)
That's because you're accessing the wrong par of state. Take a look at your combineReducers call:
export default combineReducers({
posts,
postsHasErrored,
postsIsLoading,
totalPages,
setSearchString,
setSearchCategories,
setSearchPage
})
Per the Redux documentation:
combineReducers(reducers)
The shape of the state object matches the keys of the passed reducers.
Thus your state object actually looks like this:
{
posts: ...,
postsHasErrored: ...,
postsIsLoading: ...,
totalPages: ...,
setSearchString: ...,
setSearchCategories: ...,
setSearchPage: ...
}
In your mapDispatchToProps, you're trying to access the wrong part of state:
currentPage: state.searchPage,
searchCategories: state.searchCategories,
searchString: state.searchString
Since state.searchPage and the other two don't exist in the state object, you get undefined. Instead, make sure you access the keys which have the same name as the reducers:
currentPage: state.setSearchPage,
searchCategories: state.setSearchCategories,
searchString: state.setSearchString
Or just rename your reducers (which would be preferable as they are misnomers right now). Get rid of the set prefix on the reducers, they are not actions.

Modifying state with promises

Why do my promises not actually update the state in Redux?
I'm using redux-promise-middleware. When I make a call to my API, it goes through the promise steps of _PENDING and _FULFILLED, but the state is never updated to reflect the changes.
How do I do this properly, so that I actually get my data.
Here's a picture of my state:
As you can see, isFetched does not become true after the promise is fulfilled, and data is never loading the returned response data into itself.
This is my API helper:
class UserAPI {
...
async testPhone(user) {
await axios.post(this.testPhonePath, {
phone: user.phone
})
.then(function(response) {
return response.data
})
.catch(function(error) {
return error.response.data
})
}
}
My action:
import { UserAPI } from '../../constants/api'
const userAPI = new UserAPI()
export const TEST_USER_PHONE = 'TEST_USER_PHONE'
export const testUserPhone = (user) => ({
type: TEST_USER_PHONE,
payload: userAPI.testPhone(user)
})
And my reducer:
import {
TEST_USER_PHONE
} from './actions'
const INITIAL_STATE = {
testedByPhone: {
data: [],
isFetched: false,
error: {
on: false,
message: null
}
}
}
export default (state = INITIAL_STATE, action) => {
switch(action.type) {
case '${TEST_USER_PHONE}_PENDING':
return INITIAL_STATE
case '${TEST_USER_PHONE}_FULFILLED':
return {
testedByPhone: {
data: action.payload,
isFetched: true,
error: {
on: false,
message: null
}
}
}
case '${TEST_USER_PHONE}_REJECTED':
return {
testedByPhone: {
data: [],
isFetched: true,
error: {
on: true,
message: action.payload
}
}
}
default:
return state
}
}
Here's my Store
import { createStore, applyMiddleware, compose } from 'redux'
import promiseMiddleware from 'redux-promise-middleware'
import reducers from './reducers'
const middleware = [
promiseMiddleware()
]
if (__DEV__) {
const logger = require('redux-logger')
middleware.push(logger())
}
const enhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose
export default createStore(
reducers,
undefined,
enhancers(applyMiddleware(...middleware))
)
The reason it isn't working, it is that you use a standard string instead of JS templates.
Replace:
'${TEST_USER_PHONE}_REJECTED'
With:
`${TEST_USER_PHONE}_REJECTED`
I suspect you wanted to use either
testPhone(user) {
return axios.post(this.testPhonePath, {
phone: user.phone
}).then(function(response) {
return response.data
}, function(error) {
return error.response.data
});
}
or
async testPhone(user) {
try {
const response = await axios.post(this.testPhonePath, {
phone: user.phone
});
return response.data
} catch(error) {
return error.response.data
}
}
but not that current mix which always returns a promise for undefined - it only uses await but not return.

Categories