Using async and await with export const
With export and import we are suggested to follow the model:
To define and export a function in the file myFile.js:
export const request = async (arg1, arg2) => {
try {
const response = await fetch('https://api.com/values/?arg1=' + arg1 + '&arg2=' arg2);
const json = await response.json();
console.log(json);
}
catch (e) {
console.log('We have the error', e);
}
}
To import and apply the function:
import {request} from './myFile'
request(arg1, arg2);
return dispatch => {...}
needs to also be async
I believe. Right now, only the top level function is async
, not the nested one.
// This function is async
export const loginWithToken = async () => {
// This one is not though which means it can't use await inside
// return dispatch => {
// Instead it should likely be:
return async dispatch => {
dispatch({type: SESSION_LOGIN_IN_PROGRESS, payload: true})
let storedData = await ReadFromLocalDB('user')
console.log(storedData)
if (!storedData) {
invalidToken(null, dispatch)
}
else {
storedData = JSON.parse(storedData)
SessionLoginWithToken(storedData.session.token).then(res => {
console.log(res)
loginSuccessfully(res, dispatch, true)
})
}
}
}
It looks like it's because the function you return (dispatch => {...}
) is not an async function, so you can't use await
in it. You would need to do something like return async dispatch => {...}