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.
i set my values in Async storage while logging
fetch('http://xxxxx/xxxx/getUserDetails.php', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
user_id: this.state.userEmail,
})
})
.then((response) => response.json())
.then((responseJson) => {
const name = responseJson[0]['name'];
const profilePicture = responseJson[0]['profile_picture'];
const userId = responseJson[0]['id'];
const loginMode = responseJson[0]['login_mode'];
AsyncStorage.setItem('active', 'true');
AsyncStorage.setItem('userEmail', this.state.userEmail);
AsyncStorage.setItem('name', name);
AsyncStorage.setItem('profilePicture', profilePicture);
AsyncStorage.setItem('userID', userId);
AsyncStorage.setItem('loginMode', loginMode)
setTimeout(async () => {
this.setState({ isLoading: false })
this.props.navigation.navigate('userScreen');
}, 500)
})
.catch((error) => {
console.log(error);
})
}
and delete those while logging out.
fetch('https://xxxxxx/xxxx/userLogout.php', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
email: userEmail
})
}).then((response) => response.json())
.then(async (responseJson) => {
try {
const keys = await AsyncStorage.getAllKeys();
await AsyncStorage.multiRemove(keys);
this.props.navigation.toggleDrawer();
this.setState({ isLoading: false })
this.props.navigation.navigate('loginScreen');
} catch (error) {
console.log("Error clearing app data");
}
}).catch((error) => {
console.log(error);
})
but again if i login with new user the old user details is shown in login page. if i reload my app the new values stored in async storage is shown why this is happen and this is not happening?
I am using the AsyncStorage here.
async componentDidMount() {
const userEmail = await AsyncStorage.getItem('userEmail');
const name = await AsyncStorage.getItem('name');
const profilePicture = await AsyncStorage.getItem('profilePicture');
const userID = await AsyncStorage.getItem('userID');
this.getWish();
this.getAddFunction();
this.setState({ userEmail })
this.getResumeVideo(userEmail);
this.getDemoVideo();
this.getClass();
this.setState({
userEmail,
name,
profilePicture,
userID
})
this.getNotificationCount(userID);
Orientation.lockToPortrait();
this._unsubscribe = this.props.navigation.addListener('focus', () => {
this.getAddFunction();
this.getDemoVideo();
this.getResumeVideo(this.state.userEmail);
this.getClass();
this.getNotificationCount(userID);
});
}
The only place you are calling setState and tells react it should assign new value to state (and render...) it at componentDidMount, therefore React don't know it should render again.
When assigning new value to AsyncStorage you might also call setState
fetch('http://xxxxx/xxxx/getUserDetails.php', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
user_id: this.state.userEmail,
})
})
.then((response) => response.json())
.then((responseJson) => {
const name = responseJson[0]['name'];
const profilePicture = responseJson[0]['profile_picture'];
const userId = responseJson[0]['id'];
const loginMode = responseJson[0]['login_mode'];
AsyncStorage.setItem('active', 'true');
AsyncStorage.setItem('userEmail', this.state.userEmail);
AsyncStorage.setItem('name', name);
AsyncStorage.setItem('profilePicture', profilePicture);
AsyncStorage.setItem('userID', userId);
AsyncStorage.setItem('loginMode', loginMode)
setTimeout(async () => {
this.setState({ isLoading: false })
this.props.navigation.navigate('userScreen');
}, 500)
// here
this.setState({
name,
profilePicture,
userID
})
})
.catch((error) => {
console.log(error);
})
}
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
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
});