Using [react-admin]
I have a customDashboard that verifies a parameter and redirect to the a page called pages
:
class DashBoard extends Component {
componentDidMount() {
const { push } = this.props;
if (!localStorage.getItem("activePage")) {
push("/pages");
}
...
I also have this authProvider that fetches authentication data from backend:
export default (type, params) => {
if (type === AUTH_LOGIN) {
const { authResponse } = params;
const request = new Request('https://localhost:8080/users/auth', {
method: 'POST',
body: JSON.stringify({ userID }),
headers: new Headers({ 'Content-Type': 'application/json' }),
});
fetch(request)
.then(response => {
if (response.status < 200 || response.status >= 300) {
throw new Error(response.body);
}
return response.json();
}).then(({ user }) => {
localStorage.setItem('token', user.token);
localStorage.setItem('name', user.name);
localStorage.setItem('email', user.email);
localStorage.setItem('activePage', user.activePage);
}).catch((err) => {
return Promise.reject(err);
}).finally(() => {
return Promise.resolve();});
...
I stripped down the code to show only the Promises part.
However, the last part of the code, the finally
, is being executed AFTER “/pages”
gets mounted, as I saw in the console.log. And, in “/pages”
I check the activePage returned by the backend, what is happening too late.
What is missing in the authProvider to “await” the promises get finished?
Try using async/await
, it's bit easier to follow the flow:
export default async (type, userID) => {
if (type === AUTH_LOGIN) {
try {
const res = await fetch('https://localhost:8080/users/auth', {
method: 'POST',
body: JSON.stringify({ userID })
headers: new Headers({ 'Content-Type': 'application/json' }),
}) // fetch API data
const { user: { token, name, email, activePage } } = await res.json(); // convert to JSON, from the JSON's user prop, pull out token, name, email, activePage
localStorage.setItem('token', token);
localStorage.setItem('name', name);
localStorage.setItem('email', email);
localStorage.setItem('activePage', activePage);
} catch(err) { console.error(err); }
}
}