AsyncStorage await issue with redux and axios - javascript

I need to send an axios request passing a token, this token is saved on my AsyncStorage. The problem is, when i make the call looks like its been sended without the AsyncStorage return the token, also the then/catch do not trigger.
Code example:
export const verificarPreco = (produto, estabelecimento) => {
return async dispatch => {
axios({
method: "get",
url: `${API}preco/verificarPreco/?produto=${produto}&estabelecimento=${estabelecimento}`,
headers: {
"x-access-token": await AsyncStorage.getItem("#Offer4All:token")
}
})
.then(response => {
verificarPrecoSucesso(response.data, dispatch);
})
.catch(error => {
verificarPrecoErro(error.response, dispatch);
});
};
};

You could use just async/await instead of handling the promises manually, and putting a try/catch around that.
export const verificarPreco = (produto, estabelecimento) => {
return async dispatch => {
try {
const token = await AsyncStorage.getItem("#Offer4All:token");
const request = await axios({
method: "get",
url: `${API}preco/verificarPreco/?produto=${produto}&estabelecimento=${estabelecimento}`,
headers: {
"x-access-token": token
}
});
const response = await request.json();
verificarPrecoSucesso(response.data, dispatch);
} catch (error) {
verificarPrecoErro(error.response, dispatch);
}
};
};

Related

how to get axios to return the object instead of promise

currently, my code is returning a promise I need it to return the object that It is getting from the API call, how would do that?
import axios from 'axios';
const baseUrl = 'http://api.openweathermap.org/data/2.5/weather?';
const getWeatherData = async (city,country) => {
// const result=await axios.get(`http://api.openweathermap.org/data/2.5/weather?q=${city},${country}&APPID=180941f68139fba12f166dc35d9b688b`)
// return result;
axios({
method: "GET",
url: `http://api.openweathermap.org/data/2.5/weather?q=${city},${country}&APPID=180941f68139fba12f166dc35d9b688b`,
})
.then((response) => {
return response.data;
})
.catch((error) => {
console.log(error);
});
}
export default getWeatherData;
try {
const response = await axios({
method: "GET",
url: `http://api.openweathermap.org/data/2.5/weather?q=${city},${country}&APPID=180941f68139fba12f166dc35d9b688b`,
});
return response.data;
} catch (err) {
console.error(err);
}
You can rewrite your axios call this way since your function is flagged as async.
async functions always return promises. Within async functions, you can use await infront of other async functions or functions that return promises.

dispatching Asynchronous action from an array react redux thunk

As per the requirement we need to make API call from the array list.Have used redux-thunk for async operation.Having issues while passing the request parameter to the reducer after api call is finished.
# From the container
let document = [ bankstatement1,bankstatement2];
document.map(element => {
dispatch ( actions.uploadFiles(element) )
});
# inside actions
export const uploadFiles = (payload) => {
return async dispatch => {
const response = await callAPIMiddleware(dispatch, {
types: ['DOC_UPLOAD_START','DOC_UPLOAD_SUCCESS','DOC_UPLOAD_ERROR'],
endPoint: ApiEndpoints.DOCUMENT_UPLOAD,
type: HTTP_METHOD_TYPE.POST,
payload: payload,
headers: Headers.multipart,
});
return response;
};
};
# inside axios middle ware
export const callAPIMiddleware = async (dispatch, RequestParams) => {
# calling upload_start ,here also the request payload being asked.
dispatch({
type: "DOC_UPLOAD_START,
data:RequestParams //bankstatement1,bankstatement2
});
# let res = await axios.post(endPoint,RequestParams, {
headers: reqHeaders,
config: reqConfig,
});
if (res && res.data) {
dispatch({
type:'DOC_UPLOAD_SUCCESS',
data: res.data,
param:RequestParams //bankstatement2,bankstatement2 here it is always referring to "bankstatement2"
});
}
After the API call is finished, reference to first request parameter is overridden by second one.Can anyone suggest how we can still refer to the first element .
EDITED:
what if you try to place the last piece of logic in "then" so it surely scoped there?
axios.post(endPoint,RequestParams, {
headers: reqHeaders,
config: reqConfig,
}).then(res => {
console.log('calling dispatch for ', RequestParams);
if (res && res.data) {
dispatch({
type:'DOC_UPLOAD_SUCCESS',
data: res.data,
param: RequestParams,
});
} else {
console.log('oops no result for ', RequestParams);
}
})

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 } };
};

Vue - returning the result of a synchronous method

I'm struggling to return the synchronous results of the method below.
I call the method from a different method:
var result = this.getVendor(id)
console.log(result)
Here is the fetch method:
methods: {
async getData(id) {
const response = await fetch(`${API_URL}api/${id}`, {
method: "GET",
headers: {
authorization: `Bearer ${localStorage.token}`
}
})
.then(res => res.json())
.then(data => {
return data;
});
await response;
}
}
How do I return the results response of the getData() function to show in the console?
Async functions Always return a promise.
You can use the await syntax to return it properly.
async getData(id) {
const response = await fetch(`${API_URL}api/${id}`, {
method: "GET",
headers: {
authorization: `Bearer ${localStorage.token}`
}
})
const data = await response.json()
return data
}
You can access the data out of that function anywhere you call it.
let data = null
object.getData(2)
.then(x => {
data = x
})
Also if you are going to use async await make sure to use try and catch to handle any errors that come up.
async getData(id) {
try {
const response = await fetch(`${API_URL}api/${id}`, {
method: "GET",
headers: {
authorization: `Bearer ${localStorage.token}`
}
})
const data = await response.json()
return data
}
} catch(err) {
console.error(err)
}

Async and localStorage not working properly

So I'm using React with React-Router.
I have a onEnter hook which checks if the user is authenticates yes/no and executes the desired action.
export function requireAuth(nextState, replaceState) {
if (!isAuthenticated()) {
if (!Storage.get('token')) replaceState(null, '/login');
return delegate().then(() => replaceState(null, nextState.location.pathname));
}
if (nextState.location.pathname !== nextState.location.pathname) {
return replaceState(null, nextState.location.pathname);
}
}
When the token is expired I call a delegate function which looks like:
export function delegate() {
const refreshToken = Storage.getJSON('token', 'refresh_token');
return getData(endpoint)
.then(res => {
Storage.set('token', JSON.stringify({
access_token: res.data.access_token,
refresh_token: refreshToken,
}));
});
}
The delegate function indeed refresh the tokens in the localStorage. But the requests after the replaceState are not using the updated token, but the previous one. I think this is a async issue, someone knows more about this?
Edit: The function where I use the token:
function callApi(method, endpoint, data) {
return new Promise((resolve, reject) => {
let headers = {
'Accept': 'application/json',
'X-API-Token': Storage.getJSON('token', 'access_token'),
};
const body = stringifyIfNeeded(data);
const options = { method, headers, body };
return fetch(endpoint, options)
.then(response =>
response.json().then(json => ({ json, response }))
).then(({ json, response }) => {
if (!response.ok) {
reject({ json, response });
}
resolve(json);
}).catch((error, response) => {
reject({ error, response });
});
});
}

Categories

Resources