How to use hooks inside non React component? - javascript

I'm really new to react and I have this
import Axios from "axios";
import { useAuth } from "react-oidc-context";
const ProductService = {
getProductList: () => {
return Axios({
method: "get",
url: "<myurl>",
headers: {
"Authorization": useAuth().user?.access_token
}
}).then((response) => {
return response.data;
}).catch((error) => {
console.log(error);
});
},
getProduct: (productId: string) => {
return Axios({
method: "get",
url: "<myurl>/" + productId,
headers: {
"Authorization": useAuth().user?.access_token
}
}).then((response) => {
return response.data;
}).catch((error) => {
console.log(error);
});
},
addClient: (data: any) => {
return Axios({
method: "post",
url: "<myurl>",
data: data,
headers: {
"Authorization": useAuth().user?.access_token
}
}).then((response) => {
return response.data;
}).catch((error) => {
console.log(error);
});
}
}
export default ProductService
Notice that I'm trying to use useAuth() in the Authorization header and I'm getting React Hook "useAuth" is called in function "getProductList" which is neither a React function component or a custom React Hook function.
In this case, what's the workaround so I can use useAuth() to get user token.
My Component
<Button type="submit"
onClick={() => {
ProductService.addClient(data)
.then(() => {
toggleModal();
});
}}>
Add
</Button>
Thanks

Hooks is a function that controls state management or life cycle methods of the React component through registered order. So, React Hooks are not available outside the component. Please refer to the Link.
Only Call Hooks at the Top Level. So, the getProductList should be changed as follows.
const getProductList = (access_token) => {
if (!access_token) throw new Error('No access_token');
return Axios({
method: "get",
url: "<myurl>",
headers: {
"Authorization": access_token
}
}).then((response) => {
return response.data;
}).catch((error) => {
console.log(error);
});
};
const YourReactComponent = () => {
const auth = useAuth();
useEffect(() => {
getProductList(auth?.user?.access_token)
.then(() => {
/* NEXT STEP */
})
}, [auth?.user?.access_token]);
return <>
Component Text.
</>
};

As per Hooks rule, we can use hooks only from React function components or custom Hooks.
In your scenario,
Create one React component.
Get value from "useAuth()" in above functional component.
Pass above the value to ProductService.getProductList(auth) as one of the parameter.
I hope you are calling ProductService from particular react component right. Get auth value from there and pass it to ProductService.getProductList(auth)
const ProductService = {
getProductList: (authToken: any) => {
return Axios({
method: "get",
url: "<myurl>",
headers: {
"Authorization": authToken
}
}).then((response) => {
return response.data;
}).catch((error) => {
console.log(error);
});
},
getProduct: (authToken: any, productId: string) => {
return Axios({
method: "get",
url: "<myurl>/" + productId,
headers: {
"Authorization": authToken
}
}).then((response) => {
return response.data;
}).catch((error) => {
console.log(error);
});
},
addClient: (authToken: any, data: any) => {
return Axios({
method: "post",
url: "<myurl>",
data: data,
headers: {
"Authorization": authToken
}
}).then((response) => {
return response.data;
}).catch((error) => {
console.log(error);
});
}
}
const TestReactFunctionalComponent = () => {
const auth = useAuth();
// use below calling wherever you want inside this component
ProductService.getProductList(auth.user?.access_token);
return(
// your compoent elements
)
};

Related

Work around to use custom hook in useEffect?

I have a custom hook called Api which fetches data from my API & handles my auth token and refresh tokens.
On my Main app, there are multiple ways that my state variable "postId" will be changed. And whenever it is changed, I want my API to fetch the new content for that. But I can't call my custom Api within useEffect, which is how I'm detecting changes in postId.
Can someone please suggest a workaround? I spent forever making this API, now I feel like I can't even use it.
Main.tsx:
import React, {useState, useEffect} from 'react';
import Api from './hooks/useApi';
import Modal from 'react-modal'
import Vim from './Vim';
import './Main.css';
import './modal.css';
Modal.setAppElement('#root')
function Main():JSX.Element {
const [postId,updatePostId] = useState<number|null>(null)
const [content, updateContent] = useState<string>('default text');
const [auth, updateAuth] = useState<boolean>(false)
const [authModalIsOpen, setAuthModal] = useState(false)
const [username, setUsername] = useState('')
const [password, setPassword] = useState('')
const [authKey, setAuthKey] = useState('')
const [refreshKey, setRefreshKey] = useState('eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ0b2tlbl90eXBlIjoicmVmcmVzaCIsImV4cCI6MTYxMjMzNjU4MiwianRpIjoiZTA0YjRlMjQ3MTI2NGY5ZWE4MWRiZjdiYmUzYzYwNzkiLCJ1c2VyX2lkIjoxfQ.TFBBqyZH8ZUtOLy3N-iwikXOLi2x_eKmdZuCVafPWgc')
const apiUrl = 'http://127.0.0.1:8000/'
function openAuthModal(){ setAuthModal(true) }
function closeAuthModal(){
if(auth){ setAuthModal(false) }
}
useEffect(()=>{
const props = {
username: 'raven',
password: 'asdfsdfds',
payload: {
path: 'notes/',
method: 'GET',
body: {pid: postId},
},
complete: (res:{})=>{console.log(res)},
fail: ()=>{}
}
Api(props)
},[postId])
function loadPost(pid:number):string|null{
// fetch from API, load post content
console.log('I can access:'+postId)
return null;
}
function backLinks():JSX.Element{
return(
<div className="backlinks">
</div>
)
}
function sendLogin(){
const requestOptions = {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({
username: username,
password: password
})
}
return fetch(apiUrl+'login', requestOptions)
.then(response=>response.json())
}
return (
<div className='main'>
<Vim key={postId} content={content} />
<Modal
isOpen={authModalIsOpen}
onRequestClose={closeAuthModal}
className='Modal'
overlayClassName='Overlay'
>
<form onSubmit={(e)=>{
e.preventDefault()
console.log(username)
sendLogin().then((data)=>{
if(data.auth){
updateAuth(true)
}
})
}}>
<input name='username' onChange={(e)=>{
setUsername(e.target.value)
}}/>
<input type="password" name='password' onChange={(e)=>{
setPassword(e.target.value)
}}/>
<button type="submit">Login</button>
</form>
</Modal>
</div>
)
}
export default Main
useApi.tsx:
import {useState, useEffect} from 'react'
interface IProps {
username:string,
password:string,
payload:IPayload,
complete: (result:{})=>void,
fail: ()=>void
}
interface IPayload {
path:string,
method:string,
body:{}|null,
}
function Api(props:IProps){
const [accessKey, setAccessKey] = useState('')
const [refreshKey, setRefreshKey] = useState('')
const [refreshKeyIsValid, setRefreshKeyIsValid] = useState<null|boolean>(null)
const apiUrl = 'http://127.0.0.1:8000/api/'
const [accessKeyIsValid, setAccessKeyIsValid] = useState<null|boolean>(null)
const [results, setResults] = useState<null|{}>(null)
function go(payload=props.payload){
const options = {
method: payload.method,
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer '+accessKey,
},
... (payload.body !== null) && { body: JSON.stringify(payload.body) }
}
return fetch(apiUrl+payload.path,options)
.then(response=>{
if(response.status===401){
setAccessKeyIsValid(false)
return false
} else {
return response.json()
.then(response=>{
setResults(response)
return true
})
}
})
}
useEffect(()=>{
if(results){
props.complete(results)
}
},[results])
useEffect(()=>{
if(accessKeyIsValid===false){
// We tried to make a request, but our key is invalid.
// We need to use the refresh key
const options = {
method: 'POST',
headers: { 'Content-Type': 'application/json', },
body: JSON.stringify( {'refresh': refreshKey} ),
}
fetch(apiUrl+'token/refresh/', options)
.then(response=>{
if(response.status === 401){
setRefreshKeyIsValid(false)
// this needs to trigger a login event
} else {
response.json()
.then(response=>{
setRefreshKeyIsValid(true)
setAccessKey(response.access)
setRefreshKey(response.refresh)
setAccessKeyIsValid(true)
})
}
})
}
},[accessKeyIsValid])
useEffect(()=>{
if(accessKeyIsValid===true){
// Just refreshed with a new access key. Try our request again
go()
}
},[accessKeyIsValid])
useEffect(()=>{
if(refreshKeyIsValid===false){
// even after trying to login, the RK is invalid
// We must straight up log in.
const options = {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
username: props.username,
password: props.password,
})
}
fetch(apiUrl+'api/token/', options)
.then(response=>{
if(response.status === 401){ props.fail() }
else {
response.json()
.then(response=>{
setAccessKey(response.access)
setAccessKeyIsValid(true)
})
}
})
}
},[refreshKeyIsValid])
return( go() )
};
export default Api
You can pass dependencies to your custom hooks to be passed on to any underlying hooks that may depend on them. Since I'm not very familiar with Typescript there may be some necessary type definition tweaks. I've looked over your hook logic and suggest the follow for what I think would be the correct dependencies for when postId changes.
function useApi(props: IProps, deps) { // <-- accept a dependency array arg
const [accessKey, setAccessKey] = useState("");
const [refreshKey, setRefreshKey] = useState("");
const [refreshKeyIsValid, setRefreshKeyIsValid] = useState<null | boolean>(
null
);
const apiUrl = "http://127.0.0.1:8000/api/";
const [accessKeyIsValid, setAccessKeyIsValid] = useState<null | boolean>(
null
);
const [results, setResults] = useState<null | {}>(null);
const go = useCallback(() => { // <-- memoize go callback
const { body, method, path } = props.payload;
const options = {
method,
headers: {
"Content-Type": "application/json",
Authorization: "Bearer " + accessKey
},
...(body !== null && { body: JSON.stringify(body) })
};
return fetch(apiUrl + path, options).then((response) => {
if (response.status === 401) {
setAccessKeyIsValid(false);
return false;
} else {
return response.json().then((response) => {
setResults(response);
return true;
});
}
});
}, [accessKey, props.payload, setAccessKeyIsValid, setResults]);
useEffect(() => {
if (results) {
props.complete(results);
}
}, [results, props]);
useEffect(() => {
if (accessKeyIsValid) {
// Just refreshed with a new access key. Try our request again
go();
} else {
// We tried to make a request, but our key is invalid.
// We need to use the refresh key
const options = {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ refresh: refreshKey })
};
fetch(apiUrl + "token/refresh/", options).then((response) => {
if (response.status === 401) {
setRefreshKeyIsValid(false);
// this needs to trigger a login event
} else {
response.json().then((response) => {
setRefreshKeyIsValid(true);
setAccessKey(response.access);
setRefreshKey(response.refresh);
setAccessKeyIsValid(true);
});
}
});
}
}, [accessKeyIsValid, ...deps]); // <-- pass your dependencies
useEffect(() => {
if (!refreshKeyIsValid) {
// even after trying to login, the RK is invalid
// We must straight up log in.
const options = {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
username: props.username,
password: props.password
})
};
fetch(apiUrl + "api/token/", options).then((response) => {
if (response.status === 401) {
props.fail();
} else {
response.json().then((response) => {
setAccessKey(response.access);
setAccessKeyIsValid(true);
});
}
});
}
}, [refreshKeyIsValid, ...deps]); // <-- pass your dependencies
return go();
}
Usage
useApi(props, [postId]);

Axios post is not returning data when used in a function call in a react application

I am using axios post request in my react application. The post request works fine and i get respone data in console log. But i want to return that data to render in web page. Any help is greatly appreciated. Thank you.
Here is my function that makes axios request.
function _toRoomName(title) {
const axios = require('axios');
axios({
method: "POST",
url:"hashroomname.php",
data: {
roomname: title
}
}).then((response) => {
console.log(response.data);
return response.data;
}).catch((error) => {
return error;
});
}
Here is my render method that need to render returned response.
<Text className = 'titled'>
{ _toRoomName(title) } //I want result here
</Text>
You're missing a return from the function call - you're returning from within the then but not the outer promise
function _toRoomName(title) {
return axios({
method: "POST",
url:"hashroomname.php",
data: {
roomname: title
}
}).then((response) => {
console.log(response.data);
return response.data;
}).catch((error) => {
return error;
});
}
but this won't really work. You can't embed the promise within the <Text>, you'll need to lift it outside into state
eg
const [ data, setData ] = useState(null)
useEffect(() => {
_toRoomName(title)
.then(response => {
setData(response)
})
}, [])
return (
<Text className = 'titled'>
{data}
</Text>
)
now data will be null until loaded, and <Text> will be empty until it has the data
The solution is: 1) make your function asyncronous.
async function _toRoomName(title) {
const axios = require('axios');
axios({
method: "POST",
url:"hashroomname.php",
data: {
roomname: title
}
}).then((response) => {
console.log(response.data);
return response.data;
}).catch((error) => {
return error;
});
}
2)Move your function to componentDidMount() and store the result in state. use that state in render method.
componentDidMount() {
const axios = require('axios');
axios({
method: "POST",
url:"hashroomname.php",
data: {
roomname: title
}
}).then((response) => {
this.setState({state:response.data})
}).catch((error) => {
return error;
});
}

Invalid hook call. Hooks can only be called inside of the body of a function component.?

I am struggling to solve this issue. I wanted to replace componentDidMount() with useEffect() and I got the error.
const requestData = group => {
useEffect(() => {
fetch("http://localhost:4996/getTagsFromWebsite", {
method: "POST",
headers: {
"Content-Type": "application/json;charset=utf-8",
"Access-Control-Allow-Origin": "*",
},
body: JSON.stringify(group),
})
.then(response => {
return response.json();
})
.then(data => {
console.log("request data", data);
// debugger;
setTagsData(data);
});
}, []);
};
You could call your useEffect() directly inside your component and set your requestData like so:
function App(){
const [requestData, setRequestData] = useState(null);
useEffect(() => {
fetch("http://localhost:4996/getTagsFromWebsite", {
method: "POST",
headers: {
"Content-Type": "application/json;charset=utf-8",
"Access-Control-Allow-Origin": "*",
},
body: JSON.stringify(group),
})
.then(response => {
return setRequestData(response.json());
})
.then(data => {
console.log("request data", data);
// debugger;
setTagsData(data);
});
}, []);
}
If you would like this to be a hook, call it like so:
function useRequestData(route){
const [requestData, setRequestData] = useState(null);
const [tagsData, setTagsData] = useState(null);
useEffect(() => {
fetch(route, {
method: "POST",
headers: {
"Content-Type": "application/json;charset=utf-8",
"Access-Control-Allow-Origin": "*",
},
body: JSON.stringify(group),
})
.then(response => {
return setRequestData(response.json());
})
.then(data => {
console.log("request data", data);
// debugger;
setTagsData(data);
});
}, []);
// return [loading, data]
return [!requestData, requestData, tagsData];
}
function App(){
const [loading, data, err] =
useRequestData("http://localhost:4996/getTagsFromWebsite");
return loading ? "loading..." : data.foobar;
}
Hope this helps,

In react, how to update state after doing a fetch?

I have a state which is an empty array:
constructor(props) {
super(props);
this.state = {
test_steps: [],
};
}
I need to fill up that state with the following data that get when I do a GET request:
See image
UPDATED:
export function copyTestScenarioLog(tSL) {
console.log("\nCalled copyTestScenarioLog");
let url = config.base_url + `/test_scenario_logs`;
return fetch(url, {
method: 'POST',
headers: {'Content-Type': 'application/json', 'Authorization': 'Bearer ' + getUserToken() },
body: JSON.stringify({
_id: tSL._id['$oid']
})
})
.then(res => res.json())
.then(data => {
getTestStepLogs(data)
return data;
})
.catch(err => console.log(err));
}
export function getTestStepLogs(data) {
const id = data.test_step_logs[0].$oid;
let url = config.base_url + `/test_step_logs/${id}`;
return fetch(url, {
method: 'GET',
headers: { 'Authorization': 'Bearer ' + getUserToken() }
})
.then(res => res.json())
.then(data => {
console.log(data)
return data
})
.catch(err => console.log(err));
}
How do I update my state after doing a GET fetch?
This is full react component code, you see how I call your funciton in componentDidMount, and in here I pass 'this' as an argument to copyTestScenarioLog.
import React, { Component } from 'react';
import copyTestScenarioLog from './copyTestScenarioLog';
class Component1 extends Component {
constructor(props) {
super(props);
this.state = {
test_steps: []
};
}
componentDidMount() {
var reactComponent = this;
copyTestScenarioLog('i dont konw that is tsl', reactComponent);
}
render() {
return (
<div></div>
);
}
}
export default Component1;
In 'copyTestScenarioLog', I get that ( refers to react component), and use setState function in react.
export function copyTestScenarioLog(tSL, reactComponent) {
console.log("\nCalled copyTestScenarioLog");
let url = config.base_url + `/test_scenario_logs`;
return fetch(url, {
method: 'POST',
headers: { 'Content-Type': 'application/json', 'Authorization': 'Bearer ' + getUserToken() },
body: JSON.stringify({
_id: tSL._id['$oid']
})
})
.then(res => res.json())
.then(data => {
getTestStepLogs(data)
reactComponent.setState({
test_steps: data
});
return data;
})
.catch(err => console.log(err));
}
But basically I don't use this approach, I just wanted to show that how its done, I usually use await/async or function generators, because they are better approaches. Search about them and learn to use them.
you can pass onSuccess function into your getTestStepLogs and update your state.
export function getTestStepLogs(data , onSuccess) {
const id = data.test_step_logs[0].$oid;
let url = config.base_url + `/test_step_logs/${id}`;
return fetch(url, {
method: 'GET',
headers: { 'Authorization': 'Bearer ' + getUserToken() }
}).then(resp => {
if (onSuccess)
onSuccess(resp);
}).catch(err => console.log(err));
}
and when you call getStepLogs pass onSuccess as props:
this.props.getTestStepLogs(data , (resp)=>{
this.setState({test_steps:resp});
})
if you are using the get call at multiple place, you can be little generic and try this approach.
//return here does not do anything right now
export function getTestStepLogs(data) {
return new Promise(function(resolve, reject){
const id = data.test_step_logs[0].$oid;
let url = config.base_url + `/test_step_logs/${id}`;
return fetch(url, {
method: 'GET',
headers: { 'Authorization': 'Bearer ' + getUserToken() }
})
.then(res => res.json())
.then(data => {
console.log(data)
resolve(data);
})
.catch(err => {console.log(err);
reject(err);
});
})
}
async componentDidMount() {
let data = await copyTestScenarioLog();
//now set it to state
}
For an async call, there are three states. Call initiation, call success and call failure. Say "isLoading" represents the status of the call being running in the background.
Initially =>
{
isLoading : false,
data : '',
err : ''
}
Call initiated =>
{
isLoading : true,
data : '',
err: ''
}
Call success =>
{
isLoading : false,
data : response.data
err: ''
}
Call failed =>
{
isLoading :false,
data : '',
err: err
}
Usually, the GET calls of a component are made in componentDidMount. It is also the suggested way as per the react documentation.
componentDidMount(){
//Call Initiation
this.setState({
isLoading : true,
data : '',
err: ''
});
makeApiCall(api).
then((response) => {
this.setState({
isLoading : false,
data : response.data
err: ''
});
},
(err) => {
this.setState({
isLoading :false,
data : '',
err: err
})
})
.catch((err) => {
this.setState({
isLoading :false,
data : '',
err: err
})
})
}

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