React : call async method from same file - javascript

I am trying to call removeCouponCode method which exist in same file but execution says its not defined i am not sure what is missing here.
any thoughts ?
Below is the file which i am editing & trying to make changes.
not sure what is missing.
please have a look at let me know what is missing
import React, { useState, useEffect, useMemo } from 'react';
import SessionContext from 'react-storefront/session/SessionContext';
import PropTypes from 'prop-types';
import fetch from 'react-storefront/fetch';
import get from 'lodash/get';
import { EventTracking, AnalyticsErrors } from '../analytics/Events';
import Cookies from 'js-cookie';
import constants from '../constants/configs';
import errorHandler from '../constants/apiHelpers/errorHandler';
import Helper from '../constants/helper';
import configs from '../constants/configs';
const { session, actions } = useContext(SessionContext);
const initialState = {
signedIn: false,
cart: {
items: [],
shipping_methods: [],
shippingCountry: null,
shippingMethodCode: null,
freeShipingMethod: null,
freeShippingSelected: false
},
customer: {
store_credit: {},
wishlist: { items_count: 0, items: [] },
offline: true
},
errMsg: ''
};
const initialStatusState = {
cartLoadingStatus: false,
setShippingMethodStatus: false
};
async redemptionCode({ couponCode, ...otherParams }) {
let tempSession = { ...session };
const response = await fetch('/api/cart/redemptionCode', {
method: 'post',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ couponCode, ...otherParams })
});
const result = await response.json();
if (response.ok) {
if(get(result, 'cart.prices.discounts', {}) === null){
removeCouponCode(...otherParams); //says undefined removeCouponCode here
}
}
},
async removeCouponCode({ ...otherParams }) {
let tempSession = { ...session };
const response = await fetch('/api/cart/removeCouponCode', {
method: 'post',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ ...otherParams })
});
},

You didn’t reference your function and reference your function and try or you can either modify your code as follows by declaring it as a function,
async function removeCouponCode({ ...otherParams }) {
let tempSession = { ...session };
const response = await fetch('/api/cart/removeCouponCode', {
method: 'post',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ ...otherParams })
});
}
async function redemptionCode({ couponCode, ...otherParams }) {
let tempSession = { ...session };
const response = await fetch('/api/cart/redemptionCode', {
method: 'post',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ couponCode, ...otherParams })
});
const result = await response.json();
if (response.ok) {
if(get(result, 'cart.prices.discounts', {}) === null){
await removeCouponCode(...otherParams);
}
}
}

You did not declare them as function. So you define them either this way
async function redemptionCode({ couponCode, ...otherParams }) {
let tempSession = { ...session };
const response = await fetch('/api/cart/redemptionCode', {
method: 'post',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ couponCode, ...otherParams })
});
const result = await response.json();
if (response.ok) {
if(get(result, 'cart.prices.discounts', {}) === null){
removeCouponCode(...otherParams); //says undefined removeCouponCode here
}
}
},
async function removeCouponCode({ ...otherParams }) {
let tempSession = { ...session };
const response = await fetch('/api/cart/removeCouponCode', {
method: 'post',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ ...otherParams })
});
},
Or this way
const redemptionCode = async ({ couponCode, ...otherParams }) => {
let tempSession = { ...session };
const response = await fetch('/api/cart/redemptionCode', {
method: 'post',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ couponCode, ...otherParams })
});
const result = await response.json();
if (response.ok) {
if(get(result, 'cart.prices.discounts', {}) === null){
removeCouponCode(...otherParams); //says undefined removeCouponCode here
}
}
},
const removeCouponCode = async ({ ...otherParams }) => {
let tempSession = { ...session };
const response = await fetch('/api/cart/removeCouponCode', {
method: 'post',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ ...otherParams })
});
},
Both should work!

It seems that you define this function after calling it. I think you should first define it and then call it..and you can use the arrow function.

Related

Vue send request when declared params changed from empty string

In my app I'm sending a request to my backend app from which I get a response with id like { 'id': '12345'}. I saves this id as loadId inside data, here:
export default {
name: 'SyncProducts',
data() {
return {
loadId: '',
Now I want to send another POST fetchSyncedProductsResultRequest when this data loadId change from empty. How to do so?
Below my code:
imports.js
const createApparelMagicProductsRequest = (self, products) => {
const jwtToken = self.$store.state.idToken;
console.log(products)
console.log()
const payload = JSON.stringify({ product_codes: products['product_codes'].split(',') })
return axios
.post(`/api/v1/imports/products_batches`, payload,{
headers: {
Authorization: `Bearer ${jwtToken}`,
'Content-Type': 'application/json',
'Accept': 'application/json'
}
})
.then(response => response.data['id'])
};
const fetchSyncedProductsResultRequest = (token, id) => {
return axios
.get(`/api/v1/imports/products_batches`, {
params: { id: id },
headers: {
Authorization: `Bearer ${token}`,
}
})
.then(response => {
return response.data['result']
})
};
sync_products.vue
<script>
import {
fetchSyncedProductsResultRequest,
createApparelMagicProductsRequest
} from '../../api/imports'
export default {
name: 'SyncProducts',
data() {
return {
styleCodes: [],
fetchedProductSyncResult: [],
loadId: '',
}
},
async mounted() {
await fetchSyncedProductsResultRequest(this, load.id)
this.syncedProductsFetched = true
this.pageChanged(this.currentPage)
},
async mounted() {
const jwtToken = this.$store.state.idToken;
fetchSyncedProductsResultRequest(jwtToken).then(data => {
this.fetchedProductSyncResult = data
})
},
</script>
Use a watcher on loadId that calls fetchSyncedProductsResultRequest() with the new value if it's changed from an empty string to a non-empty string:
export default {
watch: {
loadId(newValue, oldValue) {
if (!oldValue && newValue) {
const jwtToken = this.$store.state.idToken;
fetchSyncedProductsResultRequest(jwtToken, newValue).then(data => {
this.fetchedProductSyncResult = data
});
}
}
}
}
demo

How do I return an item from an async funtion

Ive been looking into trying to get information from websites using fetch. Trying async/await was my first solution, and so far it has been going well. Getting the information I needed was a breeze, but trying to retrieve that data in main is my problem. Const data in my main function even with the await tag only returns an undefined object. How can I get the data that I have in the function into my main
import React from "react";
import {
WASTEMANAGEMENT_USERNAME,
WASTEMANAGEMENT_PASSWORD,
WASTEMANAGEMENT_APIKEY_AUTH,
WASTEMANAGEMENT_APIKEY_CUSTID,
WASTEMANAGEMENT_APIKEY_DATA,
} from "#env";
async function login() {
let response = await fetch("https://rest-api.wm.com/user/authenticate", {
method: "POST",
headers: {
"content-type": "application/json",
apikey: WASTEMANAGEMENT_APIKEY_AUTH,
},
body: JSON.stringify({
username: WASTEMANAGEMENT_USERNAME,
password: WASTEMANAGEMENT_PASSWORD,
locale: "en_US",
}),
});
let res = await response.json();
const id = res.data.id;
const access_token = res.data.access_token;
response = await fetch(
`https://rest-api.wm.com/authorize/user/${id}/accounts?lang=en_US`,
{
method: "GET",
headers: {
oktatoken: access_token,
apikey: WASTEMANAGEMENT_APIKEY_CUSTID,
},
}
);
res = await response.json();
const custId = res.data.linkedAccounts[0].custAccountId;
response = await fetch(
`https://rest-api.wm.com/account/${custId}/invoice?userId=${id}`,
{
method: "GET",
headers: {
apikey: WASTEMANAGEMENT_APIKEY_DATA,
token: access_token,
},
}
);
res = await response.json();
res.body.balances.filter((item) => {
if (item.type === "Current") {
console.log(item);
return item;
}
});
}
const WasteManagementLogin = async () => {
const data = await login();
console.log(data);
};
export default WasteManagementLogin;

NextJS: TypeError: Cannot read property 'json' of undefined

I've this code into pages folder on my NextJS environment. It gets data calling an external API Rest, and it's working because the console.log(response); line show me by console the Json API response. The problem I've is that I get this error in browser:
TypeError: Cannot read property 'json' of undefined
Corresponding with this line code:
const data = await res.json();
This is the complete file with the code:
import React from "react";
import fetch from "node-fetch";
const getFetch = async (invoicesUrl, params) => {
fetch(invoicesUrl, params)
.then((response) => {
return response.json();
})
.then((response) => {
console.log(response);
})
.catch((err) => {
console.log(err);
});
};
export const getServerSideProps = async () => {
const invoicesUrl = "https://192.168.1.38/accounts/123456";
const params = {
method: "get",
headers: {
Accept: "application/json",
"Content-Type": "application/json",
},
};
const res = await getFetch(invoicesUrl, params);
const data = await res.json();
console.log("Data Json: ", data);
return { props: { data } };
};
This is the Json API response that I see by console:
{
account: [
{
id: '7051321',
type: 'probe',
status: 'open',
newAccount: [Object],
lastDate: '2020-07-04',
taxExcluded: [Object],
totalRecover: [Object],
documentLinks: []
},
]
}
Any idea how can I solve it?
Thanks in advance.
UPDATE
Here the code working good:
import React from "react";
import fetch from "node-fetch";
const getFetch = async (invoicesUrl, params) => {
return fetch(invoicesUrl, params);
};
export const getServerSideProps = async () => {
const invoicesUrl = "https://192.168.1.38/accounts/123456";
const params = {
method: "get",
headers: {
Accept: "application/json",
"Content-Type": "application/json",
},
};
try {
const res = await getFetch(invoicesUrl, params);
const data = await res.json();
console.log("Data JSON: ", data);
return { props: { data } };
} catch (error) {
console.log("Data ERROR: ", error);
}
};
There are a couple of things you have to change.
const getFetch = async (invoicesUrl, params) => {
fetch(invoicesUrl, params)
.then((response) => {
return response.json();
})
.then((response) => {
console.log(response);
return response; // 1. Add this line. You need to return the response.
})
.catch((err) => {
console.log(err);
});
};
export const getServerSideProps = async () => {
const invoicesUrl = "https://192.168.1.38/accounts/123456";
const params = {
method: "get",
headers: {
Accept: "application/json",
"Content-Type": "application/json",
},
};
const data = await getFetch(invoicesUrl, params);
// const data = await res.json(); 2. Remove this you have already converted to JSON by calling .json in getFetch
console.log("Data Json: ", data); // Make sure this prints the data.
return { props: { data } };
};
You have return statement in wrong place.
When the function is expecting a return. You need to return when the statements are executed not inside the promise then function because it is an async callback function which is not sync with the statement inside getFetchfunction. I hope i have made things clear. Below is the code which will any how return something
import React from "react";
import fetch from "node-fetch";
const getFetch = async (invoicesUrl, params) => {
return fetch(invoicesUrl, params);
};
export const getServerSideProps = async () => {
const invoicesUrl = "https://192.168.1.38/accounts/123456";
const params = {
method: "get",
headers: {
Accept: "application/json",
"Content-Type": "application/json",
},
};
try{
const res = await getFetch(invoicesUrl, params);
console.log("Data Json: ", res);
}catch(error){
console.log("Data Json: ", error);
}
return { props: { res } };
};

Issue with POST Request being passed as GET

I'm going to insert the whole module in case you need to see other aspects of the code. The call in question is the addTracks method. The project is to allow the person to search the spotify library, create a playlist of songs, then add the playlist to their account. Everything works fine, besides the tracks actually saving to the account, I get a 401 error on the API, but both Chrome and FireFox also label it as a GET call, instead of as a POST. The error is an authentication error, but I should be authorized correctly, the only odd thing for authorization is the scope, which is taken care of in the redirect in getAccessToken(). What am I missing here? In case you need it: Spotify add track documentation
let accessToken;
let expiresIn;
const clientId = '86f8f621d81a4ce18bd21da9fd2da2b1';
const redirectURI = 'http://localhost:3000/';
const Spotify = {
getAccessToken() {
if (accessToken) {
return accessToken;
} else if (window.location.href.match(/access_token=([^&]*)/) != null) {
accessToken = window.location.href.match(/access_token=([^&]*)/)[1];
expiresIn = window.location.href.match(/expires_in=([^&]*)/)[1];
window.setTimeout(() => accessToken = '', expiresIn * 1000);
window.history.pushState('Access Token', null, '/');
} else {
window.location = `https://accounts.spotify.com/authorize?client_id=${clientId}&response_type=token&scope=playlist-modify-public&redirect_uri=${redirectURI}`;
}
},
async search(term) {
if (accessToken === undefined) {
this.getAccessToken();
}
try {
let response = await fetch(`https://api.spotify.com/v1/search?type=track&q=${term}`, {
method: 'GET',
headers: {
Authorization: `Bearer ${accessToken}`
}
});
if (response.ok) {
let jsonResponse = await response.json();
let tracks = jsonResponse.tracks.items.map(track => ({
id: track.id,
name: track.name,
artist: track.artists[0].name,
album: track.album.name,
uri: track.uri
}));
return tracks;
}
} catch (error) {
console.log(error);
}
},
async savePlaylist(name, trackURIs) {
if (accessToken === undefined) {
this.getAccessToken();
}
if (name === undefined || trackURIs === undefined) {
return;
} else {
let userId = await this.findUserId();
let playlistID;
fetch(`https://api.spotify.com/v1/users/${userId}/playlists`, {
method: 'POST',
headers: {
Authorization: `Bearer ${accessToken}`,
"Content-Type": 'application/json'
},
body: JSON.stringify({
name: name
})
}).then(response => {
return response.json()
}).then(playlist => {
playlistID = playlist.id;
this.addTracks(playlistID, trackURIs, userId);
});
}
},
addTracks(playlistID, trackURIs, userId) {
console.log(trackURIs);
fetch(`https://api.spotify.com/v1/users/${userId}/playlists/${playlistID}/tracks`), {
method: 'POST',
headers: {
Authorization: `Bearer ${accessToken}`,
"Content-Type": 'application/json'
},
body: JSON.stringify({
uris: trackURIs
})
}
},
findUserId() {
if (accessToken === undefined) {
this.getAccessToken();
}
let userId;
return fetch(`https://api.spotify.com/v1/me`, {
headers: {
Authorization: `Bearer ${accessToken}`
}
}).then(response => {
return response.json()
}).then(jsonResponse => {
userId = jsonResponse.id;
return userId;
});
}
};
export default Spotify;
I'm beginner but probably you should check bracket in fetch() method in addTracks()
addTracks(playlistID, trackURIs, userId) {
console.log(trackURIs);
fetch(`https://api.spotify.com/v1/users/${userId}/playlists/${playlistID}/tracks`->)<-, {
method: 'POST',
headers: {
Authorization: `Bearer ${accessToken}`,
"Content-Type": 'application/json'
},
body: JSON.stringify({
uris: trackURIs
})
}
},
correct
addTracks(playlistID, trackURIs, userId) {
console.log(trackURIs);
fetch(`https://api.spotify.com/v1/users/${userId}/playlists/${playlistID}/tracks`, {
method: 'POST',
headers: {
Authorization: `Bearer ${accessToken}`,
"Content-Type": 'application/json'
},
body: JSON.stringify({
uris: trackURIs
})
})
},

AsyncStorage.getItem returning undefined when using fetch - React-Native

I'm trying to set a token in my SignIn component using a promise and AsyncStorage but when I go to retrieve the token for use in a different component I get the error Cannot read property 'getItem' of undefined. I tried using Async/Await to wait for the token response in order to save it to storage but i've been getting the same error. How can I properly set the token?
SignIn.js Component
//Function is bound
async signIn() {
const data = JSON.stringify({username: this.state.username, password: this.state.password})
await fetch(`https://somesecretdomain.com:8443/users/login`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
},
body: data
}).then((response) => response.json()).then(async(responseJson) => {
AsyncStorage.setItem('jwt', responseJson.id_token);
const resetAction = NavigationActions.reset({
index: 0,
actions: [NavigationActions.navigate({routeName: 'Profile'})]
});
this
.props
.navigation
.dispatch(resetAction);
}).catch((error) => {
console.warn(error);
})
};
Profile.js Component
async fetchData() {
AsyncStorage
.getItem('jwt')
.then((value) => {
this.setState({"TOKEN": value});
})
.done();
console.log(this.state.TOKEN)
const response = await
fetch(`https://somesecretdomain.com:8443/users/getUsers`, {
method: 'GET',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
'token': this.state.TOKEN
}
})
const json = await response.json()
}
I changed the Profile.js component to below, still getting the same error.
import React, {AsyncStorage, localStorage} from 'react';
import {
Text,
View,
Image,
TouchableHighlight,
WebView,
TextInput,
KeyboardAvoidingView,
ScrollView
} from 'react-native';
async fetchData() {
const TOKEN = await AsyncStorage.getItem('jwt');
const response = await
fetch(`https://somedomain.com:8443/users/getUsers`, {
method: 'GET',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
'token' : TOKEN
},
});
const result = await response.json();
this.setState({data: result})
}
Try this:
async signIn() {
const data = JSON.stringify({username: this.state.username, password: this.state.password})
const response = await fetch(`https://somesecretdomain.com:8443/users/login`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
},
body: data
});
const result = await response.json();
await AsyncStorage.setItem('jwt', result.id_token);
const resetAction = NavigationActions.reset({
index: 0,
actions: [NavigationActions.navigate({routeName: 'Profile'})]
});
this
.props
.navigation
.dispatch(resetAction);
});
};

Categories

Resources