Axios put return undefined [React JS + Axios] - javascript

Hi all im doing an axios put to update my data. However im getting an undefined response. Thank you in advance
function that call the Axios:
export function exUpdateMovie(movie) {
Axios.put(baseURL + "/api/update", {
movieName: movie.movieName,
movieReview: movie.movieReview,
id: movie.id,
})
.then((response) => {
// console.log(response);
return response;
})
.catch((e) => {
console.log(e);
return e;
});
}
function in app.js that calls the exUpdateMovie(movie) function:
const handleUpdateMovie = (movie) => {
console.log("UpdateMovie Passed!");
try {
const res = exUpdateMovie(movie);
alert(res?.data);
} catch (error) {
console.log(error);
}
};
Output when I alert my response is:
undefined
SETTLE:
need to add async and await at the handleUpdateMovie
need to return the Axios by doing return Axios.put()
Cheers mate for helping me. Thanks alot

Yes because your api call is returning a promise where you need to wait until the promise execution completes so make your function async and wrap the API call with await.
export async function exUpdateMovie(movie) {
const result = await Axios.put(baseURL + "/api/update", {
movieName: movie.movieName,
movieReview: movie.movieReview,
id: movie.id,
})
return result
}
const handleUpdateMovie = async (movie) => {
console.log("UpdateMovie Passed!");
try {
const res = await exUpdateMovie(movie);
alert(res?.data);
} catch (error) {
console.log(error);
}
};

Because exUpdateMovie doesn't return anything. Return the Promise:
export function exUpdateMovie(movie) {
return Axios.put(/* all your Axios code */);
}
Then when consuming the result, treat it as a Promise:
exUpdateMovie(movie).then(res => {
alert(res?.data);
});

Related

What if axios call in getServerSideProps() failed? How to repeat

I'm trying to pre render page using getServerSideProps in Next.js and everything works perfectly.
But what if the axios call failed due to server issue or Network error?
How can I repeat the call?
Here's my code:
export async function getServerSideProps() {
let ImagesList = {};
await axios
.get("https://www.*****.com/api/home")
.then((response) => {
if (response.data) {
ImagesList = response.data
}
})
.catch((err) => { });
return {
props: {
ImagesList,
}
}
}
you can try to wrap your axios call inside a while loop,
let result = false;
while(!result) {
await axios
.get("https://www.*****.com/api/home")
.then((response) => {
result = true
if (response.data) {
ImagesList = response.data
}
})
.catch((err) => { });
}

How to handle "Promise { <pending> }" in javascript

I have this function in javascript
const getData = async() => {
try {
const serviceResponse = await someService("userId")
return serviceResponse
} catch (error) {
console.log(error);
}
}
const data = getData()
console.log(data)
Whenever I am running this I am getting this in console
Promise { <pending> }
But when I am print data in the function itself I am getting the desired value
const getData = async() => {
try {
const serviceResponse = await someService("userId")
console.log.(serviceResponse)
} catch (error) {
console.log(error);
}
}
getData()
The following function is what I am importing from defined in another another
exports.someService = async(date,locationId,workerType) => {
const value = await Attendance.find({})
return value
}
Please can someone explain what is happening ?
you need to await the promise from getData() too -
const data = await getData()

how to use axios to capture http json response and pass value to another function?

I am trying to perform a GET call in typescript to various services and capture a value from their json response which will be passed in as a param in another function.
Through some online searching, I bumped into axios but am having a hard time wrapping my head around asynchronous apis and how to handle promises. Here is the code, that returns 'undefined' as an output.
function getVersion(url: string) {
let version;
let res = await axios.get(url)
.then((response: { data: { buildInfo: { details: { version: any; }; }; }; }) => {
version = response.data.buildInfo.details.version;
return version;
})
.catch((error: any) => {
console.log(error);
});
return version;
}
I've also tried async/await but have trouble with unhandled promises. I don't need to use axios, any library will do as long as I can access the response to use in consequent functions.
you can return a promise for getVersion()
async function getVersion(url: string) {
let res = await axios.get(url)
.then((response: { data: { buildInfo: { details: { version: any; }; }; }; }) => {
let version = response.data.buildInfo.details.version;
return new Promise((resolutionFunc) => { // return a promise
resolutionFunc(version);
});
})
.catch((error: any) => {
console.log(error);
});
return res;
}
getVersion(url).then(res => {console.log(res)}) // use
or you can just return the axios, beacuse axios will return a promise
async function getVersion(url: string) {
let res = await axios.get(url)
return res;
}
getVersion(url).then(res => {console.log(res)}) // use

how to return value from a promise function

I have a function which checks whether a device is online or not. Below is the code.
const ping = require('ping');
export function findDevices(device) {
try {
const hosts = [device];
let result = null;
hosts.forEach((host) => {
ping.promise.probe(host)
.then((res) => {
console.log(res.alive)
result = res.alive;
return {
Status: result
}
});
});
} catch (err) {
logger.error(err, '[ config - findDevices() ]');
console.error(err);
return {
Status: "Failed"
}
}
}
I am calling this function in a redux action like this:
export function start(device) {
return dispatch => {
const status = Connectionstatus.findDevices(device);
return dispatch({
type: actionTypes.CONNECTIONSTATUS,
payload: {
ConnectionStatus: status
}
})
};
}
I am expective the status variable to be either true or false. But i am getting as undefined even though i am returning the value inside then of the promise function. i have tried awaiting this call and still its not working. Any help would be much appreciated. Thanks.
If that's the case you can do like this
const getStatus = async () => {
try {
const hosts = [device];
const promises = [];
hosts.forEach((host) => {
promises.push(ping.promise.probe(host));
});
const result = await Promise.all(promises);
const status = result.map((r) => { return r.alive; });
return status;
} catch (err) {
logger.error(err, '[ config - findDevices() ]');
return { status: 'Failed' };
}
};
Not 100% sure what all the vars are, but have you considered using async/await to simplify things a bit like this?
const getStatus122 = async device => {
return await Promise.all([device].map(ping.promise.probe))
.then(({ alive }) => alive)
.then(Status => ({ Status }))
.catch(error => {
logger.error(error, '[ config - findDevices() ]');
return { Status: 'Failed' };
})
}
More on that here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function
With Promises you should inspect the promised result either in when or catch callback functions. With async/await the code may look a bit simpler. Here is the version with explicit promises.
const ping = require('ping');
const Connectionstatus = {
findDevices: (device) => {
return ping.promise.probe(device).then((res) => {
const result = res.alive;
console.log(result);
return {
Status: result,
};
}).catch((err) => {
logger.error(err, '[ config - findDevices() ]');
console.error(err);
return {
Status: "failed"
}
});
}
}
export function start(device) {
return dispatch => {
Connectionstatus.
findDevices(device).
then((status) => {
dispatch({
type: actionTypes.CONNECTIONSTATUS,
payload: {
ConnectionStatus: status
}
})
});
};
}
You may see that error handling moved to the catch callback function while the dispatch is done in the then callback function. And this is the answer to your question.

Export function with promise, wait for response

I'm calling a function inside a then statement, and that function has to wait for an event to fire, but my initial function is returning undefined almost immediately:
// call.js
const dialogflow = require('./dialogflow')
module.exports = {
receive: functions.https.onRequest((request, response) => {
...
let respondToUser = getUserId
.then((uid) => {
payload.uid = uid
dialogflow.handleIncoming(payload).then((result) => {
console.log(result)
})
})
.then((result) => {
console.log(result)
response.end()
})
...
}
}
// dialogflow.js
module.exports = {
handleIncoming: (payload) => {
...
let df = dialogflow.textRequest(message.message, {
sessionId: payload.from
})
.on('response', (response) => {
return response.result.fulfillment.speech
})
.on('error', (error) => {
return 'That\'s an error on my end. Try again later!'
})
.end()
}
}
The goal is to call dialogflow.handleIncoming(payload) from call.js, wait for it to return some text, and then continue. But no matter how I have structured it, receive just keeps blowing through it and dialogflow.handleIncoming(payload) ends up undefined.
I've tried using a promise on df with no success, and I can't figure out how to make respondToUser wait for a full response from handleIncoming. Everything else is working so I'm only including relevant code.
This is using api.ai (dialogflow), but in cloud functions in Firebase if that helps. Appreciate any help!
Problem is dialogflow.handleIncoming(payload) is not structured for async. Try this:
// dialogflow.js
exports.handleIncoming = (payload) =>
new Promise((resolve, reject) => {
...
let df = dialogflow.textRequest(message.message, {
sessionId: payload.from
})
.on('response', (response) => {
resolve(response.result.fulfillment.speech)
})
.on('error', (error) => {
reject ('That\'s an error on my end. Try again later!')
})
.end()
}
Your receive function isn't waiting for dialogflow.handleIncoming(payload) to complete. The then function that contains it doesn't have a return statement, so it's returning undefined rather than returning the result of dialogflow.handleIncoming (which is what you want).
let respondToUser = getUserId
.then((uid) => {
payload.uid = uid
return dialogflow.handleIncoming(payload)
})
.then((result) => {
console.log(result)
response.end()
})
The next then statement will contain the response from diagflow.handleIncoming.

Categories

Resources