Reputation: 21
I am trying to access the res.data.id from a nested axios.post call and assign it to 'activeId' variable. I am calling the handleSaveAll() function on a button Click event. When the button is clicked, When I console the 'res.data.Id', its returning the value properly, but when I console the 'activeId', it's returning null, which means the 'res.data.id' cannot be assigned. I just need to assign the value from 'res.data.id' to 'metricId' so that I can use it somewhere else in another function like save2() function. Does anyone have a solution? Thanks in advance
const [activeId, setActiveId] = useState(null);
useEffect(() => {}, [activeId]);
const save1 = () => {
axios.get(api1, getDefaultHeaders())
.then(() => {
const data = {item1: item1,};
axios.post(api2, data, getDefaultHeaders()).then((res) => {
setActiveId(res.data.id);
console.log(res.data.id); // result: e.g. 10
});
});
};
const save2 = () => {
console.log(activeId); // result: null
};
const handleSaveAll = () => {
save1();
save2();
console.log(activeId); // result: again its still null
};
return (
<button type='submit' onClick={handleSaveAll}>Save</button>
);
Upvotes: 0
Views: 345
Reputation: 221
This part of code run sync
const handleSaveAll = () => {
save1();
save2();
console.log(activeId); // result: again its still null
};
but there you run async
axios.get(api1, getDefaultHeaders())
.then(() => {
You can refactor your code to async/await like this:
const save1 = async () => {
const response = await axios.get(api1, getDefaultHeaders());
const response2 = await axios.post(api2, { item1: response.data.item1 }, getDefaultHeaders());
return response2.data.id;
};
const save2 = (activeId) => {
console.log(activeId); // result: null
};
const handleSaveAll = async () => {
const activeId = await save1();
save2(activeId);
setActiveId(activeId);
console.log(activeId); // result: again its still null
};
or to chain of promises, like this:
const save2 = (activeId) => {
console.log(activeId); // result: null
};
const save1 = () => {
return axios.get(api1, getDefaultHeaders())
.then(({ data }) => {
const data = {item1: item1,};
return axios.post(api2, {item1: data.item1}, getDefaultHeaders())
})
.then((res) => res.data.id);
};
const handleSaveAll = () => {
save1()
.then((res) => {
setActiveId(res.data.id);
console.log(res.data.id); // result: e.g. 10
return res.data.id;
})
.then(save2);
};
Upvotes: 1