There are a few ways you could solve this, the easiest of which is probably to just pass the token from the first request down to the saveCard
method -
axios
.request(options)
.then(function (response) {
console.log(response.data.id);
setToken(response.data.id)
// This gets passed to the next function in the chain
return response.data.id;
})
.then(function(token) {
saveCard(token);
})
.catch(function (error) {
console.error(error);
});
And actually - you don't need to isolate the saveCard
into a separate then
callback -
axios
.request(options)
.then(function ({ data }) {
const token = data.id;
setToken(token);
saveCard(token);
})
.catch(function (error) {
console.error(error);
});
But, if you really want to call the saveCard
method using the token from the setState
call, you're going to have to use a useEffect
. You could do something like this:
// Presuming you have something that represents your form state
const [formData, setFormData] = useState({});
const [token, setToken] = useState("");
const [submitting, setSubmitting] = useState(false);
const handleSubmit = async () => {
if (submitting) return;
setSubmitting(true);
try {
const { data } = await axios.request(options);
setToken(data.id);
} catch (error) {
console.error(error);
setSubmitting(false);
}
};
useEffect(() => {
// We can only call 'save' if we are in "submitting" mode,
// and we have a token.
if (!(submitting && token)) return;
saveData();
// You'd probably have to reset your token here too presuming
// you need to fetch another one again when you save.
setToken("");
setSubmitting(false);
}, [submitting, token, formData]
As you can see it's a lot more awkward; so I guess you have to ask yourself, do you REALLY need the token as state? The cleanest solution would be to remove it entirely, and use async/await
instead of promises:
try {
// Get the token
const { data } = await axios.request(options);
const { id: token } = data;
// Now use the token to submit the form - I'm presuming this is async too?
await saveCard(token);
} catch (error) {
console.error(error);
}