Warn : Possible Unhandled Promise Rejection (id: 0) - javascript

I am building ecommerce app using react-native I just encountered an error which i don't know what it mean
Error is "Possible Unhandled Promise Rejection (id: 0):
TypeError: undefined is not an object (evaluating 'err.response.data')"
I have used "err.response.data" in 2-3 file but i have mentioned code of one file
import AsyncStorage from '#react-native-community/async-storage';
import axios from 'axios';
import {returnErrors} from './errorActions';
import {ADD_TO_CART, CHECK_OUT} from './types';
import {
AllDispatchProp,
API_URI,
CLEAR_ERRORS,
DELETE_PRODUCT,
LOADED_PRODUCTS,
LOADING_PRODUCTS,
SENT_PRODUCT,
} from './types';
export const addProduct = ({
title,
price,
imageUrl,
desc,
}: {
title: string;
price: string;
imageUrl: string;
desc: string;
}) => async (dispatch: AllDispatchProp, getState: any) => {
const auth = getState().auth;
const data = JSON.stringify({title, price, imageUrl, desc, user: auth.user});
const token = AsyncStorage.getItem('#user_token');
//* Store a product
axios({
method: 'POST',
url: `${API_URI}/api/product`,
data,
headers: {
'content-type': 'application/json',
'x-app-token': token,
},
})
.then((res) => {
dispatch({type: CLEAR_ERRORS, payload: null});
dispatch({type: SENT_PRODUCT, payload: res.data._doc});
})
.catch((err) => {
dispatch(
returnErrors(
err.response.data,
err.response.status,
'PRODUCT_POST_FAIL',
),
);
});
};
//* Load Amazon Products *//
export const loadProducts = () => async (dispatch: AllDispatchProp) => {
dispatch({type: LOADING_PRODUCTS, payload: null});
const token = await AsyncStorage.getItem('#user_token');
//* Load products from url *//
axios({
method: 'GET',
url: `${API_URI}/api/product`,
headers: {
'content-type': 'application/json',
'x-app-token': token,
},
})
.then((res) => {
dispatch({type: LOADED_PRODUCTS, payload: res.data});
})
.catch((err) => {
dispatch(
returnErrors(
err.response.data,
err.response.status,
'LOAD_PRODUCT_FAIL',
),
);
});
};
export const deleteProduct = (_id: string) => async (
dispatch: AllDispatchProp,
) => {
const data = JSON.stringify({_id});
const token = await AsyncStorage.getItem('#user_token');
axios({
method: 'DELETE',
url: `${API_URI}/api/product`,
data,
headers: {
'content-type': 'application/json',
'x-app-token': token,
},
})
.then((res) => {
dispatch({type: DELETE_PRODUCT, payload: res.data._id});
})
.catch((err) => {
dispatch(
returnErrors(
err.response.data,
err.response.status,
'DELETE_PRODUCT_FAIL',
),
);
});
};
//* Amazon add to cart *//
export const addToCart = (_id: string) => async (
dispatch: AllDispatchProp,
getState: any,
) => {
const {products, cartProducts} = getState().product;
const cartProduct = cartProducts.filter((p: any) => p._id === _id);
const isInCart = cartProduct.length > 0;
const data = JSON.stringify({_id});
const token = await AsyncStorage.getItem('#user_token');
if (!isInCart) {
axios({
method: 'PUT',
url: `${API_URI}/api/product`,
headers: {
'content-type': 'application/json',
'x-app-token': token,
},
data,
})
.then((res) => {
dispatch({type: ADD_TO_CART, payload: res.data});
})
.catch((err) => {
dispatch(
returnErrors(
err.response.data,
err.response.status,
'ADD_TO_CART_FAIL',
),
);
});
}
};
export const productCheckOut = () => async (dispatch: AllDispatchProp) => {
const token = await AsyncStorage.getItem('#user_token');
axios({
method: 'GET',
url: `${API_URI}/api/product`,
headers: {
'content-type': 'application/json',
'x-app-token': token,
},
})
.then((res) => {
dispatch({type: CHECK_OUT, payload: res.data});
})
.catch((err) => {
dispatch(
returnErrors(err.response.data, err.response.status, 'CHECKOUT_FAIL'),
);
});
};
export const clearCart = () => async (dispatch: AllDispatchProp) => {
const token = await AsyncStorage.getItem('#user_token');
axios({
method: 'PUT',
url: `${API_URI}/api/product/clear`,
headers: {
'x-app-token': token,
},
})
.then(() => {
return loadProducts();
})
.catch(() => {});
};
I dont from where this error occurred but I really need help in this on
This is the "returnErrors" file
import {GET_ERRORS, CLEAR_ERRORS} from './types';
// RETURN ERRORS
export const returnErrors = (
msg: string,
status: string | number,
id: string | null,
) => {
return {
type: GET_ERRORS,
payload: {msg, status, id},
};
};
// CLEAR ERRORS
export const clearErrors = () => {
return {
type: CLEAR_ERRORS,
};
};
After editing;
import AsyncStorage from '#react-native-community/async-storage';
import axios from 'axios';
import {returnErrors} from './dist/errorActions';
import {ADD_TO_CART, CHECK_OUT} from './dist/types';
import {
AllDispatchProp,
API_URI,
CLEAR_ERRORS,
DELETE_PRODUCT,
LOADED_PRODUCTS,
LOADING_PRODUCTS,
SENT_PRODUCT,
} from './types';
export const addProduct = ({
title,
price,
imageUrl,
desc,
}: {
title: string;
price: string;
imageUrl: string;
desc: string;
}) => async (dispatch: AllDispatchProp, getState: any) => {
const auth = getState().auth;
const data = JSON.stringify({title, price, imageUrl, desc, user: auth.user});
const token = AsyncStorage.getItem('#user_token');
//* Store a product
axios({
method: 'POST',
url: `${API_URI}/api/product`,
data,
headers: {
'content-type': 'application/json',
'x-app-token': token,
},
})
.then((res) => {
dispatch({type: CLEAR_ERRORS, payload: null});
dispatch({type: SENT_PRODUCT, payload: res.data._doc});
})
.catch((err) => {
dispatch(
returnErrors(
err.response?.data ?? 'your default msg',
err.response?.status ?? 'your default status',
'PRODUCT_POST_FAIL',
),
);
});
};
//* Load app Products *//
export const loadProducts = () => async (dispatch: AllDispatchProp) => {
dispatch({type: LOADING_PRODUCTS, payload: null});
const token = await AsyncStorage.getItem('#user_token');
//* Load products from url *//
axios({
method: 'GET',
url: `${API_URI}/api/product`,
headers: {
'content-type': 'application/json',
'x-app-token': token,
},
})
.then((res) => {
dispatch({type: LOADED_PRODUCTS, payload: res.data});
})
.catch((err) => {
dispatch(
returnErrors(
err.response.data,
err.response.status,
'LOAD_PRODUCT_FAIL',
),
);
});
};
export const deleteProduct = (_id: string) => async (
dispatch: AllDispatchProp,
) => {
const data = JSON.stringify({_id});
const token = await AsyncStorage.getItem('#user_token');
axios({
method: 'DELETE',
url: `${API_URI}/api/product`,
data,
headers: {
'content-type': 'application/json',
'x-app-token': token,
},
})
.then((res) => {
dispatch({type: DELETE_PRODUCT, payload: res.data._id});
})
.catch((err) => {
dispatch(
returnErrors(
err.response.data,
err.response.status,
'DELETE_PRODUCT_FAIL',
),
);
});
};
//* app add to cart *//
export const addToCart = (_id: string) => async (
dispatch: AllDispatchProp,
getState: any,
) => {
const {products, cartProducts} = getState().product;
const cartProduct = cartProducts.filter((p: any) => p._id === _id);
const isInCart = cartProduct.length > 0;
const data = JSON.stringify({_id});
const token = await AsyncStorage.getItem('#user_token');
if (!isInCart) {
axios({
method: 'PUT',
url: `${API_URI}/api/product`,
headers: {
'content-type': 'application/json',
'x-app-token': token,
},
data,
})
.then((res) => {
dispatch({type: ADD_TO_CART, payload: res.data});
})
.catch((err) => {
dispatch(
returnErrors(
err.response.data,
err.response.status,
'ADD_TO_CART_FAIL',
),
);
});
}
};
export const productCheckOut = () => async (dispatch: AllDispatchProp) => {
const token = await AsyncStorage.getItem('#user_token');
axios({
method: 'GET',
url: `${API_URI}/api/product`,
headers: {
'content-type': 'application/json',
'x-app-token': token,
},
})
.then((res) => {
dispatch({type: CHECK_OUT, payload: res.data});
})
.catch((err) => {
dispatch(
returnErrors(err.response.data, err.response.status, 'CHECKOUT_FAIL'),
);
});
};
export const clearCart = () => async (dispatch: AllDispatchProp) => {
const token = await AsyncStorage.getItem('#user_token');
axios({
method: 'PUT',
url: `${API_URI}/api/product/clear`,
headers: {
'x-app-token': token,
},
})
.then(() => {
return loadProducts();
})
.catch(() => {});
};
and returnErrors file
Note: when i am editing returnError code i got an error "Unexpected Token" on question mark symbol
import {GET_ERRORS, CLEAR_ERRORS} from './types';
// RETURN ERRORS
export const returnErrors = (
msg: string | undefined,
status: string | number | undefined,
id: string | null,
) => {
return {
type: GET_ERRORS,
payload: {msg??"your default msg", status??"your default status", id},
};
};
// CLEAR ERRORS
export const clearErrors = () => {
return {
type: CLEAR_ERRORS,
};
};
One more thing whenever i'm trying to register in app it throw this error only(i hope u understand what i'm trying to say)

Maybe you can check if the params for returnErrors() exist before passing them
.catch((err) => {
dispatch(
returnErrors(
err.response?.data ?? "your default msg",
err.response?.status ?? "your default status",
'PRODUCT_POST_FAIL',
),
);
});
or you can teach your returnErrors function how to deal with undefined params
export const returnErrors = (
msg: string | undefined,
status: string | number | undefined,
id: string | null,
) => {
return {
type: GET_ERRORS,
payload: {msg:msg??"your default msg", status:status??"your default status", id},
};
};

You would have to provide the signature of the returnErrors function for a better analysis but I think this function expects an object as its first argument while err.response.data could be undefined. That would throw a type error in an asynchronous part of the code, resulting in the Unhandled Promise Rejection.
To resolve this, you could check the kind of data you send to returnErrors every time you call it, or make the function returnErrors receive any kind of data and format it accordingly. I would rather implement the latter.

Related

I'm getting API Error when I try to login after added next.js to my react app

I migrated and added Next.js to my React app. I getting the following error when I try to login. When I checked seems that I have to use promise.all. I tried different solutions without success. I want to know how it works. Your help and advice are highly appreciated.
error message;
Unhandled Runtime Error
Error: Objects are not valid as a React child (found: [object Promise]). If you meant to render a collection of children, use an array instead.
src/action/auth.js;
import axios from 'axios';
import { setAlert } from './alert';
// import { API_URL } from '../config/index';
import {
LOGIN_SUCCESS,
LOGIN_FAIL,
SIGNUP_SUCCESS,
SIGNUP_FAIL,
ACTIVATION_SUCCESS,
ACTIVATION_FAIL,
USER_LOADED_SUCCESS,
USER_LOADED_FAIL,
AUTHENTICATED_SUCCESS,
AUTHENTICATED_FAIL,
PASSWORD_RESET_SUCCESS,
PASSWORD_RESET_FAIL,
PASSWORD_RESET_CONFIRM_SUCCESS,
PASSWORD_RESET_CONFIRM_FAIL,
LOGOUT
} from './types';
export const checkAuthenticated = () => async dispatch => {
if (typeof window !== 'undefined' ? window.localStorage.getItem('access') : false) {
const config = {
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
}
};
const body = JSON.stringify({ token: typeof window !== 'undefined' ? window.localStorage.getItem('access') : false });
try {
const res = await axios.post(`${process.env.NEXT_PUBLIC_API_URL}/auth/jwt/verify/`, body, config)
if (res.data.code !== 'token_not_valid') {
dispatch({
type: AUTHENTICATED_SUCCESS
});
} else {
dispatch({
type: AUTHENTICATED_FAIL
});
}
} catch (err) {
dispatch({
type: AUTHENTICATED_FAIL
});
}
} else {
dispatch({
type: AUTHENTICATED_FAIL
});
}
};
export const load_user = () => async dispatch => {
if (typeof window !== 'undefined' ? window.localStorage.getItem('access') : false) {
const config = {
headers: {
'Content-Type': 'application/json',
'Authorization': `JWT ${typeof window !== 'undefined' ? window.localStorage.getItem('access') : false}`,
'Accept': 'application/json'
}
};
try {
const res = await axios.get(`${process.env.NEXT_PUBLIC_API_URL}/auth/users/me/`, config);
dispatch({
type: USER_LOADED_SUCCESS,
payload: res.data
});
}catch (err) {
dispatch({
type: USER_LOADED_FAIL
});
}
} else {
dispatch({
type: USER_LOADED_FAIL
});
}
};
export const login = (email, password) => async dispatch => {
const config = {
headers: {
'Content-Type': 'application/json'
}
};
const body = JSON.stringify({ email, password });
try {
const res = await axios.post(`${process.env.NEXT_PUBLIC_API_URL}/auth/jwt/create/`, body, config);
dispatch({
type: LOGIN_SUCCESS,
payload: res.data
});
dispatch(setAlert('Authenticated successfully', 'success'));
dispatch(load_user());
}catch (err) {
dispatch({
type: LOGIN_FAIL
});
dispatch(setAlert('Error Authenticating', 'error'));
}
};
export const signup = (name, email, password, re_password) => async dispatch => {
const config = {
headers: {
'Content-Type': 'application/json'
}
};
const body = JSON.stringify({ name, email, password, re_password });
try {
const res = await axios.post(`${process.env.NEXT_PUBLIC_API_URL}/auth/users/`, body, config);
dispatch({
type: SIGNUP_SUCCESS,
payload: res.data
});
dispatch(setAlert('Check Your Email to Activate Your Account.', 'warning'));
} catch (err) {
dispatch({
type: SIGNUP_FAIL
})
}
};
export const verify = (uid, token) => async dispatch => {
const config = {
headers: {
'Content-Type': 'application/json'
}
};
const body = JSON.stringify({ uid, token });
try {
await axios.post(`${process.env.NEXT_PUBLIC_API_URL}/auth/users/activation/`, body, config);
dispatch({
type: ACTIVATION_SUCCESS,
});
dispatch(setAlert('Account Activated Successfully.', 'success'));
} catch (err) {
dispatch({
type: ACTIVATION_FAIL
})
}
};
//Reset Password
export const reset_password = (email) => async dispatch => {
const config = {
headers: {
'Content-Type': 'application/json'
}
};
const body = JSON.stringify({ email });
try {
await axios.post (`${process.env.NEXT_PUBLIC_API_URL}/auth/users/reset_password/`, body, config);
dispatch({
type: PASSWORD_RESET_SUCCESS
});
dispatch(setAlert('Check Your Email to Rest Password.', 'warning'));
} catch (err) {
dispatch({
type: PASSWORD_RESET_FAIL
});
}
};
// Reset Password Confirm
export const reset_password_confirm = (uid, token, new_password, re_new_password) => async dispatch => {
const config = {
headers: {
'Content-Type': 'application/json'
}
};
const body = JSON.stringify({ uid, token, new_password, re_new_password });
try {
await axios.post (`${process.env.NEXT_PUBLIC_API_URL}/auth/users/reset_password_confirm/`, body, config);
dispatch(setAlert('Password Rest Successful.', 'success'));
dispatch({
type: PASSWORD_RESET_CONFIRM_SUCCESS
});
} catch (err) {
dispatch({
type: PASSWORD_RESET_CONFIRM_FAIL
});
}
};
//Logout
export const logout = () => dispatch => {
dispatch(setAlert('Logout successful.', 'success'));
dispatch({
type: LOGOUT
});
};
src/pages/login.js;
import React, { useState } from 'react';
import Link from 'next/link';
import { useRouter } from 'next/router';
import { connect } from 'react-redux';
import { Button } from '#mui/material';
import { login } from '../actions/auth';
import styles from '../styles/Login.module.css';
import Head from 'next/head';
import WelcomePageFooter from '../components/WelcomePageFooter';
import { serverSideTranslations } from 'next-i18next/serverSideTranslations';
import { useTranslation } from 'next-i18next';
import i18n from '../../i18n';
function Login({ login, isAuthenticated }) {
const { t } = useTranslation();
const navigate = useRouter();
const [formData, setFormData] = useState({
email: '',
password: ''
});
const { email, password } = formData;
const onChange = e => setFormData({ ...formData, [e.target.name]: e.target.value});
const onSubmit = e => {
e.preventDefault();
login (email, password)
};
if (isAuthenticated) {
return (
navigate.replace('/')
);
}
return (
<main>
<div className={styles.login}>
<Head>
<title>Diploman - Login</title>
<meta
name='description'
content='login page'
/>
</Head>
<h1 className={styles.login__title}>{t('login_title')}</h1>
<p className={styles.login__lead}>{t('login_lead')}</p>
<form className={styles.login__form} onSubmit={e => onSubmit(e)}>
<div className={styles.login__form__group}>
<input
className={styles.login__form__input}
type='email'
placeholder={t('Form_email')}
name='email'
value={email}
onChange={e => onChange(e)}
required
/>
</div>
<div className={styles.login__form__group}>
<input
className={styles.login__form__input}
type='password'
placeholder={t('Form_pw')}
name='password'
value={password}
onChange={e => onChange(e)}
minLength='8'
required
/>
</div>
<Button className={styles.login__button__main} type='submit'>{t('login_title')}</Button>
</form>
<p className={styles.link__to__Signup}>
{t('login_text1')} <Link href='/signup' className={styles.login__link}>{t('login_register')}</Link>
</p>
<p className={styles.link__to__resetPassword}>
{t('login_text2')} <Link href='/reset-password' className={styles.reset__password__link}>{t('login_reset')}</Link>
</p>
</div>
<WelcomePageFooter/>
</main>
)
};
export const getServerSideProps = async ({ locale }) => (
{ props: {
...(await serverSideTranslations(
locale,
['common'],
i18n,
)),
} }
);
const mapStateToProps = state => ({
isAuthenticated: state.auth.isAuthenticated
});
export default connect (mapStateToProps, { login }) (Login);
I really appreciate your help here

React Redux Thunk with callback to another function -- TypeError: Cannot read property 'then' of undefined

I am using react+redux.
I have a modal form with data and images and on success I need to close the modal else display error returned from redux. In the dispatch function I have 1 more callback function to store images to S3. I am returning promise from the redux-thunk but I keep getting "TypeError: Cannot read property 'then' of undefined".
Component
handleSubmit = e => {
e.preventDefault();
if(this.isFieldEmpty()){
this.setState({ message: "All fields are mandatory with at least 1 pic" });
return;
} else {
this.setState({ message: "" });
}
const data = {
name: this.state.name,
description : this.state.description,
points : this.state.points,
attributes : this.state.attributes,
images : this.state.images,
created_by: localStorage.getItem('id'),
}
this.props.createItem(data).then(() => {
this.hideModal();
})
}
const mapDispatchToProps = dispatch => {
return {
createItem: data => {
return dispatch(createItem(data))
},
};
};
Action
const saveItemImages = (images,successcb, failurecb) => {
if(images.length > 0){
const formData = new FormData();
for(var x = 0; x<images.length; x++) {
formData.append('image', images[x])
}
const token = localStorage.getItem('token');
fetch(`${backendUrl}/upload/item-images/`, {
method: "POST",
headers: {
'Authorization': `Bearer ${token}`
},
credentials: 'include',
body: formData
})
.then(res => {
if(res.status === 200){
res.json().then(resData => {
successcb(resData.imagesUrl);
});
}else{
res.json().then(resData => {
failurecb(resData.message);
})
}
})
.catch(err => {
console.log(err);
});
} else {
successcb([]);
}
}
export const createItem = data => { return (dispatch) => {
saveItemImages(data.images, imagesUrl => {
data.images = imagesUrl;
return fetch(`${backendUrl}/admin/createItem`, {
method: 'POST',
headers: {
'Accept': 'application/json, text/plain, */*',
'Content-Type': 'application/json',
'Authorization': `Bearer ${data.token}`
},
credentials: 'include',
body: JSON.stringify(data)
})
.then(res => {
if(res.status === 200){
res.json().then(resData => {
dispatch({
type: ADMIN_CREATE_ITEM_SUCCESS,
payload: resData
})
return true;
});
}else{
console.log("Save failed");
res.json().then(resData => {
dispatch({
type: ADMIN_CREATE_ITEM_FAILED,
payload: {
message: resData.message
}
})
})
}
})
.catch(err => {
dispatch({
type: ADMIN_CREATE_ITEM_FAILED,
payload: {
message: `Internal Error -- ${err}`
}
})
});
}, failedMessage => {
let payload = {responseMessage: failedMessage}
dispatch({
type: ADMIN_CREATE_ITEM_FAILED,
payload: payload
})
});
};
};
Thanks in advance for any help
You should return a Promise to create async flow for the action like this:
export const createItem = data => dispatch => new Promise((resolve, reject) => {
// do something was a success
resolve();
// do something was a fail
reject();
});

ReactJS: How to implement react-cookie properly in an action?

I have read articles that saving the token in localstorage is dangerous to XSS attack. So I have decided to store my tokens in cookies. And I am using react-cookie. I saw the examples and I am trying to do it but my auth.js consists of const and is not a class, so I do not know how to use the withCookies() with it, this is my auth.js where I want to store the token to the cookies:
import {
LOGIN,
LOGIN_SUCCESS,
LOGIN_FAILED,
GET_USER_DATA,
GET_USER_DATA_SUCCESS,
GET_USER_DATA_FAILED,
LOGOUT,
LOGOUT_SUCCESS,
LOGOUT_FAILED,
} from './types'
import axios from 'axios'
var api = require ('./../api.js');
export const login = (email, pass) => {
return (dispatch) => {
dispatch({
type: LOGIN
})
var url = api.logInApi
axios.post(url, {
email: email,
password: pass
})
.then(res => {
dispatch({
type: LOGIN_SUCCESS,
payload: res.data
})
localStorage.setItem('token', res.data.token)
dispatch(getUserData())
})
.catch(err => dispatch({
type: LOGIN_FAILED,
payload: err
}))
}
}
export const getUserData = () => {
return (dispatch) => {
dispatch({
type: GET_USER_DATA
})
var url = api.getUserDataApi
axios.post(url, {}, {headers: {
"Authorization": `Bearer ${localStorage.getItem("token")}`
}})
.then(res => {
dispatch({
type: GET_USER_DATA_SUCCESS,
payload: res.data
})
})
.catch(err => dispatch({
type: GET_USER_DATA_FAILED,
payload: err
}))
}
}
export const logout = () => {
return (dispatch) => {
dispatch({
type: LOGOUT
})
var url = api.logoutApi
axios.post(url, {}, {headers: {
"Authorization": `Bearer ${localStorage.getItem("token")}`
}})
.then(res => {
window.location.replace("")
dispatch({
type: LOGOUT_SUCCESS,
payload: res.data
})
})
.catch(err => dispatch({
type: LOGOUT_FAILED,
payload: err
}))
}
}
Now, I tried doing this and of course it doesn't work:
import {
LOGIN,
LOGIN_SUCCESS,
LOGIN_FAILED,
GET_USER_DATA,
GET_USER_DATA_SUCCESS,
GET_USER_DATA_FAILED,
LOGOUT,
LOGOUT_SUCCESS,
LOGOUT_FAILED,
} from './types'
import axios from 'axios'
import { withCookies, Cookies } from 'react-cookie'; <<added this
var api = require ('./../api.js');
const login = (email, pass) => {
return (dispatch) => {
dispatch({
type: LOGIN
})
const { cookies } = props; <<added this
var url = api.logInApi
axios.post(url, {
email: email,
password: pass
})
.then(res => {
dispatch({
type: LOGIN_SUCCESS,
payload: res.data
})
cookies.set('token', res.data.token, { path: '/' }); <<added this
dispatch(getUserData())
})
.catch(err => dispatch({
type: LOGIN_FAILED,
payload: err
}))
}
}
export default withCookies(login) <<added this(wrong)
const getUserData = () => {
return (dispatch) => {
dispatch({
type: GET_USER_DATA
})
const { cookies } = props; <<added this
var token = cookies.get('token'); <<added this
var url = api.getUserDataApi
axios.post(url, {}, {headers: {
"Authorization": `Bearer ${token}` <<added this(this is where I wanna get the cookie)
}})
.then(res => {
dispatch({
type: GET_USER_DATA_SUCCESS,
payload: res.data
})
})
.catch(err => dispatch({
type: GET_USER_DATA_FAILED,
payload: err
}))
}
}
export default withCookies(getUserData) <<added this(wrong)
const logout = () => {
return (dispatch) => {
dispatch({
type: LOGOUT
})
const { cookies } = props;
var token = cookies.get('token');
var url = api.logoutApi
axios.post(url, {}, {headers: {
"Authorization": `Bearer ${token}` <<added this
}})
.then(res => {
window.location.replace("")
dispatch({
type: LOGOUT_SUCCESS,
payload: res.data
})
})
.catch(err => dispatch({
type: LOGOUT_FAILED,
payload: err
}))
}
}
export default withCookies(logout) <<added this(wrong)
this one is wrong because there should only be one export default. But I don't know how to implement withCookies to const and there are also these ones that are included in the example and I don't know if I need them or where do I put them:
static propTypes = {
cookies: instanceOf(Cookies).isRequired
};
constructor(props) {
super(props);
const { cookies } = props;
this.state = {
name: cookies.get('name') || 'Ben'
};
}
and also, another question is that, I can access my cookies anywhere in my project right? just like how localstorage is accessible to my project?
I hope someone can help me and I am a newbie to this. I have never used cookies before so thank you for your consideration.
I personally would rather using js-cookie to write/read cookies.
It has a very basic API:
Cookie.set('cookie_name', 'value') // will set "cookie_name" to "value"
Cookie.get('cookie_name') // will return "value"
Which means:
const login = (email, pass, cookie) => {
return (dispatch) => {
dispatch({
type: LOGIN
})
var url = api.logInApi
axios.post(url, {
email: email,
password: pass
})
.then(res => {
dispatch({
type: LOGIN_SUCCESS,
payload: res.data
})
cookies.set('token', res.data.token);
dispatch(getUserData())
})
.catch(err => dispatch({
type: LOGIN_FAILED,
payload: err
}))
}
}
Passing to the login funuction js-cookie's Cookie in the 3rd argument.
Now, you can still use the same react-cookie package to read the cookie values (I believe there shouldn't be any conflicts). Or you can replace it with js-cookie. To do that, however, you will have to pass the Cookie object to props. I probably would do that using mapStateToProps if you're using Redux or just by simply passing it through JSX

React-Redux syntax error "," expected

New to this.
...and this is probably very simple. I have looked at the code for the const "selectData" and I cannot find where a comma is suppose to go. Here is the entire file:
export const requestLoginToken = (username, password) =>
(dispatch, getState) => {
dispatch({ type: REQUEST_LOGIN_TOKEN, payload: username })
const payload = {
userName: username,
password: password,
}
const task = fetch('/api/jwt', {
method: 'POST',
body: JSON.stringify(payload),
headers: {
'Content-Type': 'application/json;charset=UTF-8'
},
})
.then(handleErrors)
.then(response => response.json())
.then(data => {
dispatch({ type: RECEIVE_LOGIN_TOKEN, payload: data })
saveJwt(data)
selectData()
})
.catch(error => {
clearJwt()
dispatch({ type: ERROR_LOGIN_TOKEN, payload: error.message })
})
addTask(task)
return task
}
const selectData = () => {
dispatch({ type: REQUEST_SELECT_DATA })
const token = jwt.access_token
const headers = new Headers({
'Authorization': `Bearer ${token}`
})
const selectData = fetch('/api/SelectData/SelectData', {
method: 'GET',
headers,
})
.then(handleErrors)
.then(response => response.json())
.then(data => {
dispatch({ type: RECEIVE_SELECT_DATA, payload: data })
.catch(error => {
clearJwt()
dispatch({ type: ERROR_SELECT_DATA, payload: error.message })
})
}
}
The error is on the very last curly bracket and it says:
Unexpected token, expected , (72:0)
line 72 is the last curly bracket.
If I remove the const expression that is "selectData" its OK - no errors. The error only appears when I add in that block of code... i.e its in the following:
const selectData = () => {
dispatch({ type: REQUEST_SELECT_DATA })
const token = jwt.access_token
const headers = new Headers({
'Authorization': `Bearer ${token}`
})
const selectData = fetch('/api/SelectData/SelectData', {
method: 'GET',
headers,
})
.then(handleErrors)
.then(response => response.json())
.then(data => {
dispatch({ type: RECEIVE_SELECT_DATA, payload: data })
.catch(error => {
clearJwt()
dispatch({ type: ERROR_SELECT_DATA, payload: error.message })
})
}
}
Why is this block of code causeing an error?
You forgot a ) on the last then:
.then(data => {
dispatch({ type: RECEIVE_SELECT_DATA, payload: data })
.catch(error => {
clearJwt()
dispatch({ type: ERROR_SELECT_DATA, payload: error.message })
})
}) // <--- here
And you should always use ;. I recommend you to use a linter to check your code, like ESLint

React Redux promise error - (...).then is not a function

Had a look for this in the questions that offered but this was the closest and it didnt really address my problem.
I have a code block (detailed a little way down the page) as part of a larger fetch block.. it gets to this codeblock and also runs fine if this code block is commented out i.e it carrys out a successful fetch etc and returns a JWT no problem but... add this block in and i get the following error:
TypeError: (0 , _localStorageDropDowns.confirmSelectDataExistance)(...).then is not a function
It is referring to this function in another folder (imported correctly)..
export const confirmSelectDataExistance = () => {
const companyStateShortNameJson = localStorage.getItem(COMPANYSTATESHORTNAME)
const statesJson = localStorage.getItem(STATES)
const suburbLocationsJson = localStorage.getItem(LOCATIONS)
if (companyStateShortNameJson || statesJson || suburbLocationsJson) {
console.log('something exists in localstorage')
return true
}
console.log('nothing in localstorage')
return false
}
simple function - returns true or false.
and here is the code block -its failing on the first line:
return confirmSelectDataExistance().then(isConfirmed => {
if (!isConfirmed) {
dispatch({ type: REQUEST_SELECT_DATA })
console.log('gets here!', isConfirmed)
const token = getJwt()
const headers = new Headers({
'Authorization': `Bearer ${token}`
})
const retrieveSelectData = fetch('/api/SelectData/SelectData', {
method: 'GET',
headers: {
'Content-Type': 'application/json;charset=UTF-8'
},
})
.then(handleErrors)
.then(response => response.json())
.then(selectData => {
dispatch({ type: RECEIVE_SELECT_DATA, payload: selectData })
saveSelectData(selectData)
});
return saveSelectData(selectData);
}
})
From my limited experience the "confirmSelectDataExistance" is a function so why is it saying that its not?
Finally here is the whole action in its entirety so you can see how it that block is called.. as I said - comment the block out and it works perfectly..
export const requestLoginToken = (username, password) =>
(dispatch, getState) => {
dispatch({ type: REQUEST_LOGIN_TOKEN, payload: username })
const payload = {
userName: username,
password: password,
}
const task = fetch('/api/jwt', {
method: 'POST',
body: JSON.stringify(payload),
headers: {
'Content-Type': 'application/json;charset=UTF-8'
},
})
.then(handleErrors)
.then(response => response.json())
.then(data => {
dispatch({ type: RECEIVE_LOGIN_TOKEN, payload: data })
saveJwt(data)
return confirmSelectDataExistance().then(isConfirmed => {
if (!isConfirmed) {
dispatch({ type: REQUEST_SELECT_DATA })
console.log('gets here!', isConfirmed)
const token = getJwt()
const headers = new Headers({
'Authorization': `Bearer ${token}`
})
const retrieveSelectData = fetch('/api/SelectData/SelectData', {
method: 'GET',
headers: {
'Content-Type': 'application/json;charset=UTF-8'
},
})
.then(handleErrors)
.then(response => response.json())
.then(selectData => {
dispatch({ type: RECEIVE_SELECT_DATA, payload: selectData })
saveSelectData(selectData)
});
return saveSelectData(selectData);
}
})
})
.catch(error => {
clearJwt()
console.log('ERROR - LOGIN!',error)
})
addTask(task)
return task
}
EDIT
I have finally got this to work after hacking away for hours.. Here is the finished action:
export const requestLoginToken = (username, password) =>
(dispatch, getState) => {
dispatch({ type: REQUEST_LOGIN_TOKEN, payload: username })
const payload = {
userName: username,
password: password,
}
const task = fetch('/api/jwt', {
method: 'POST',
body: JSON.stringify(payload),
headers: {
'Content-Type': 'application/json;charset=UTF-8'
},
})
.then(handleErrors)
.then(response => response.json())
.then(data => {
dispatch({ type: RECEIVE_LOGIN_TOKEN, payload: data })
saveJwt(data)
// Now check local storage for dropdown data..
if (!confirmSelectDataExistance()) {
dispatch({ type: REQUEST_SELECT_DATA })
const token = JSON.stringify(data)
const headers = new Headers({
'Authorization': `Bearer ${token}`
})
const retrieveSelectData = fetch('/api/SelectData/SelectData', {
method: 'GET',
headers: {
'Content-Type': 'application/json;charset=UTF-8'
},
})
.then(handleErrors)
.then(response => response.json())
.then(selectData => {
dispatch({ type: RECEIVE_SELECT_DATA, payload: selectData })
saveSelectData(selectData)
});
}
})
.catch(error => {
clearJwt()
console.log('ERROR - LOGIN!', error)
})
addTask(task)
return task
}
and here is the function it calls:
export const confirmSelectDataExistance = () => {
const companyStateShortNameJson = localStorage.getItem(COMPANYSTATESHORTNAME)
const statesJson = localStorage.getItem(STATES)
const suburbLocationsJson = localStorage.getItem(LOCATIONS)
if (companyStateShortNameJson || statesJson || suburbLocationsJson) {
console.log('something exists in localstorage')
return true
}
console.log('nothing in localstorage')
return false
}
The one thing I changed from the other attempts is that I used "data" instead of calling "getJwt()". I then used the line:
const token = JSON.stringify(data)
to obtain the JWT I just got.
In the end I used #Karin s answer and ran with that. (upvoted by me)
The error is not saying that confirmSelectDataExistance is not a function, it's saying that then isn't a function on what is returned from it, which is a boolean (it would be equivalent to false.then(...), which doesn't work).
If seems like you're trying to use then as a conditional. In that case a simple if statement should work:
if (confirmSelectDataExistance()) {
// do things if it returns true
} else {
// do things if it returns false
}
export const confirmSelectDataExistance = () => {
return new Promise(function (resolve, reject) {
const companyStateShortNameJson = localStorage.getItem(COMPANYSTATESHORTNAME)
const statesJson = localStorage.getItem(STATES)
const suburbLocationsJson = localStorage.getItem(LOCATIONS)
if (companyStateShortNameJson || statesJson || suburbLocationsJson) {
console.log('something exists in localstorage')
resolve(true)
}
console.log('nothing in localstorage')
reject(false)
})
}
Try something like this:
export const confirmSelectDataExistance = new Promise((resolve, reject) => {
const companyStateShortNameJson = localStorage.getItem(COMPANYSTATESHORTNAME);
const statesJson = localStorage.getItem(STATES);
const suburbLocationsJson = localStorage.getItem(LOCATIONS);
if (companyStateShortNameJson || statesJson || suburbLocationsJson) {
console.log('something exists in localstorage');
resolve(true);
}
console.log('nothing in localstorage');
reject(false); // or resolve(false) if you want handle this situation inside then block also
});

Categories