Axios.get not returning any data - reactjs

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

Related

axios returns "fullfilled" promise

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

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

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

How to get data from response if you receive an error?

How do I get a backend error if I get a 404?
Here is my code:
export const myRequest = async (body: params) => {
try {
const result = await publicInstance.get('users', {
params: body,
});
const { data } = result;
return data;
} catch (error) {
console.error('Error:', error.message, error); // How to get data from response?
}
return {};
};
You will get the statusCode in the response, which you can track. Based on the status code you can put your customized error message.
export const myRequest = async (body: params) => {
try {
const result = await publicInstance.get('users', {
params: body,
});
const { data } = result;
return data;
} catch (error) {
if(error.statusCode == 404)
error.message = "Unable to reach server at the moment. Please try again."
console.error('Error:', error.message, error);
}
return {};
};

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