Reputation: 2127
async function submitForm(e){
e.preventDefault()
console.log(e.target)
await axios.post('/api/<PATH>', {username, password})
.then(res => {
console.log(res.data)
const token = res.data.token
if (token){
const json = jwt.decode(token) as { [key: string]: string}
await axios.post('/api/<PATH>', { token })
.then(res => {
const data = res.data
The issue is on this line
await axios.post('/api/<PATH>', { token })
My IDE states
TS1308: 'await' expressions are only allowed within async functions and at the top levels of modules.
It currently cannot compile, I am trying to pass the token value into another axios API call. However this is currently not possible because of the error above. Any clue on how to fix this will be appreciated
Upvotes: 0
Views: 206
Reputation: 20885
await
must be directly in an async
function, you need to make the callback function async
as well.
async function submitForm(e){
e.preventDefault()
console.log(e.target)
await axios.post('/api/<PATH>', {username, password})
// async here
.then(async res => {
console.log(res.data)
const token = res.data.token
if (token){
const json = jwt.decode(token) as { [key: string]: string}
await axios.post('/api/<PATH>', { token })
.then(res => {
const data = res.data
As Bergi mentioned, there's no point to mix await
and .then
, your code could be like this:
async function submitForm(e){
e.preventDefault()
console.log(e.target)
let res = await axios.post('/api/<PATH>', {username, password})
console.log(res.data)
const token = res.data.token
if (token){
const json = jwt.decode(token) as { [key: string]: string}
res = await axios.post('/api/<PATH>', { token })
const data = res.data;
Upvotes: 2