axios returns "fullfilled" promise - reactjs

Can someone please tell me why my Axios service function returns this:
The object looks fine in the service function.
Promise {<fulfilled>: {…}}
[[Prototype]]: Promise
[[PromiseState]]: "fulfilled"
[[PromiseResult]]: Object
Here is the call:
useEffect(() => {
setData(playlistService.getPlaylists);
}, []);
console.log(data);
And the function:
const config = {
headers: {
'Content-Type': 'application/json',
},
withCredentials: true,
};
const getPlaylists = async () => {
try {
const res = await axios.get(`${API_SONGS_URL}/`, config);
console.log('RES ', res);
return res;
} catch (error) {
if (error.response) {
return error.response.data;
}
}
};

this could work
useEffect(() => {
const fetchPlayListAsync = async () => {
const response = await playlistService.getPlaylists();
setData(response)
}
fetchPlayListAsync()
}, []);
you can add appropriate checks of fetched data

Related

async function in react component isn't working when triggered from the axios request

network.services.js
axiosCall = (axiosURL) => {
// const axiosURL = "https://api.github.com/user"
axios.get(axiosURL, {
headers: {
'Authorization': `qwdvryjutmnevw`,
}
}).then((res) => {
console.log(res.data);
return res.data;
}).catch((error) => {
throw error.message;
// console.error(error);
// toast.error(error.message);
})
}
component.js
const getData = async () => {
const asyncExample = async () => {
const result = await networkServices.axiosCall("/api/v1/calendars");
const responseData = await result;
console.log(responseData);
return responseData;
}
const data = asyncExample()
data.then(function(result) {
console.log(result); // "Some User token"
})
}
Trying to get data from service to my component in const result, console form service is consoling data but component is always returning undefined instead of data from the service file. SetTimeout function is also not working in component.
You have many mistakes. I advise you to take a look at documentation about Promises
First one:
You don't return data in axiosCall
A way to return data:
axiosCall = (axiosURL) => new Promise((resolve, reject) => {
axios.get(axiosURL, {
headers: {
'Authorization': `yourTokenHere`,
}
}).then((res) => {
// return a response data
resolve(res.data);
}).catch((error) => {
// return only error message
reject(error.message);
})
})
to use axiosCall:
try {
// don't forgot to configure axios with base url
const data = await axiosCall('/api/v1/calendars');
// do something with your data
} catch (e) {
// do something with error message
console.log(e);
}
Second:
Your make mistakes when call async function
Look at this example:
const getData = () => {
networkServices
.axiosCall("/api/v1/calendars")
.then(function(result) {
// when promise resolve
console.log(result);
})
.catch(error => {
// when promise reject
console.log(error)
})
}

Axios.get not returning any data

I can not get the right info on my API.
i tried this and nothing comes back
const res = () => {
axios.get('https://api.scripture.api.bible/v1/bibles', {
headers: {
'api-key': '5b5d4503884b7a2515e8cee8f4b00746',
},
})
}
Your code works fine, but you are not doing anything with the response. axios.get() returns a Promise, so you need to handle it using .then()
const res = () => {
axios.get("https://api.scripture.api.bible/v1/bibles", {
headers: {
"api-key": "5b5d4503884b7a2515e8cee8f4b00746"
}
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
};
res();
or make an async function and use async await.
const res = async () => {
try {
const response = await axios.get("https://api.scripture.api.bible/v1/bibles", {
headers: {
"api-key": "5b5d4503884b7a2515e8cee8f4b00746"
}
});
console.log(response);
} catch (error) {
console.log(error);
}
};
res();
Instead of console.logging you can do anything, for example use a callback function:
const res = async (callback, errorCallback) => {
try {
const response = await axios.get("https://api.scripture.api.bible/v1/bibles", {
headers: {
"api-key": "5b5d4503884b7a2515e8cee8f4b00746"
}
});
callback(response);
} catch (error) {
errorCallback(error);
}
};
const onSuccess = result => {
const data = JSON.stringify(result);
alert(data)
};
const onError = error => {
alert(`Ops! An error occured: ${error}`);
};
res(onSuccess, onError);

how to use aync and await inside use effect of calling function?

I am calling following functions like below.
How I can give async await to the serviceRequest and success handler
useEffect(() => {
serviceRequest(
"URL",
success,
error
);
}, []);
const success = (response) => { }
const error = (error) => { }
export const serviceRequest = (endpoint,successCallBack,errorCallBack) => {
const options: any = {
withCredentials: true,
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
}
}
axios.get(endpoint, options)
.then((response) => {
successCallBack(response.data)
})
.catch(error => {errorCallBack(error) })
}
Well, first make sure that the serviceRequest function returns a promise. In this case you could simply return the axios result:
export const serviceRequest = (endpoint,successCallBack,errorCallBack) => {
const options: any = {
withCredentials: true,
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
}
}
return axios.get(endpoint, options)
}
Then you can use the promise in your use-effect handler, catching the result / error in a useState hook like this:
const [result, setResult] = useState(null);
const [error, setError] = useState(null);
useEffect(() => {
serviceRequest("URL")
.then((result) => setState(result)
.catch(error => setState(error)
};
}, []);
You can decalre an async function in the useEffect and call it:
useEffect(() => {
const callApi = async () => {
await serviceRequest("URL", success, error);
};
callApi();
}, []);
You could write something like:
useEffect(() => {
(async () => {
await serviceRequest("URL", success, error);
})()
}, []);

How to change this promise returned function into an async await?

Initially I write my code with promise based script .then().catch
But when I tried to change it into the async await function. Its not working anymore.
Please someone help me with this.
My Old Code Which is working
export const fetchToken = (params) => {
return (dispatch) => {
const config = {
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
};
return axios
.post(`/api/token`, params, config)
.then((res) => {
tokenData = res.data.access_token;
dispatch({
type: LOGGED_IN,
payload: res.data,
});
})
.catch((err) => {
console.log(err);
alert('Provided username and password is incorrect');
throw err;
});
};
};
As you can see in the above code the function is returning a promise. But When I try to change it into async await
My simulator is give me Unexpected reserved work await Error
Here is my async await code in redux
export const fetchToken = async (params) => {
return (dispatch) => {
const config = {
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
};
try {
const response = await axios.post(`/api/token`, params, config);
const data = await response.json();
tokenData = data.access_token
dispatch({ type: LOGGED_IN, payload: res.data})
} catch {
console.log(err);
alert('Provided username and password is incorrect');
}
};
};
Your async is applied to the wrong function, it should be on the dispatch function
export const fetchToken = (params) => (
async (dispatch) => {
const config = {
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
};
try {
const response = await axios.post(`/api/token`, params, config);
const data = await response.json();
tokenData = data.access_token
dispatch({ type: LOGGED_IN, payload: res.data})
} catch {
console.log(err);
alert('Provided username and password is incorrect');
}
};
);
NB: I've removed the braces; arrow function return is implied https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions

useEffect wait for a result from the async function

I'm trying to create a function for POST request in React app (due to I need it in few places), it should return a responseText in the useEffect statement. the variant I've googled doesn't act as async - the string console.log("JSON", json) put into the console JSON undefined before the getting response from server...
useEffect(() => {
(async function() {
try {
const response = await post_return(postData);
const json = await JSON.stringify(response);
console.log("json", json);
} catch (e) {
console.error(e);
}
})();
}, [postData]);
const API_URL_REGISTRATION = "https:.....";
export function post_return (dataPost) {
var xhr = new XMLHttpRequest();
xhr.open("POST", API_URL_REGISTRATION, true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.onreadystatechange = function () {
if (xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) {
console.log("xhr.status", this.status);
console.log("this.responseText", this.responseText);
return xhr.status
}
};
xhr.onload = function () {
console.log("xhr.status", this.status);
console.log("this.responseText", this.responseText);
return xhr.status;
};
xhr.onerror = function () {
alert('Error' + this.status);
};
xhr.send(JSON.stringify(dataPost));
}
tried also:
export async function post_return (dataPost) {...
and:
xhr.onreadystatechange = async function ()
What I do wrong?
Thanks,
First thing that is wrong with post_return function is it returns undefined immediately, hence the response variable value is actually undefined and a result of calling JSON.stringify with undefined is also undefined. What you should do is to correct post_return so that it returns a Promise.
Simplest solution would be to use built-in fetch like so:
export function async post_return (dataPost) {
const response = await fetch(API_URL_REGISTRATION, {
method: 'POST',
body: JSON.stringify(dataPost),
headers: {
'Content-type': 'application/x-www-form-urlencoded'
}
});
if (response.ok) {
return response.json();
}
// Here you can do some basic error parsing/handling
throw new Error();
}
Rafal2228, thanks for your post, I adopted it for my needs
export async function post_return(url, dataPost) {
const response = await fetch(url, {
method: 'POST',
body: JSON.stringify(dataPost),
headers: {
'Content-type': 'application/x-www-form-urlencoded'
}
});
const json = await response.json();
return {
status: response.status,
body: json
};
}
useEffect(() => {
(async function() {
try {
if (postData.email !== undefined)
{
const response = await post_return(API_URL_REGISTRATION, postData);
// console.log("response", response);
setshowLoader(false);
if (response.status === 200) {
navigate("/login")
} else alert(response.body);
}
} catch (e) {
console.error('Ошибка ' , e);
}
})();
}, [postData]);

Resources