Aldo
Aldo

Reputation: 1287

authProvider is finishing its Promise after the Dashboard being mounted

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?

Upvotes: 1

Views: 776

Answers (2)

Matt Carlotta
Matt Carlotta

Reputation: 19762

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); }
  }
}

Upvotes: 2

Aldo
Aldo

Reputation: 1287

Digging around I found this answer and did some changes in my code. Now it works fine:

  • The default function is async, calls an auth function and returns a Promise in the end.

    // in src/authProvider.js
    export default async (type, params) => {
        if (type === AUTH_LOGIN) {    
            const { authResponse } = params;
            const user = await auth(userID);
            localStorage.setItem('token', user.token);
            if (user.activePage) localStorage.setItem('activePage', user.activePage);
    
            return Promise.resolve();
    
  • The auth function returns a Promise:

    const auth = async (userID) => {
      const request = new Request('https://localhost:8080/users/auth', {
        method: 'POST',
        body: JSON.stringify({ userID }),
        headers: new Headers({ 'Content-Type': 'application/json' }),
      });
    
      return fetch(request)
        .then(response => {
          if (response.status < 200 || response.status >= 300) {
            throw new Error(response.body);
          }
          return response.json();
        })
        .then(({ user }) => {
          return user;
        });
    }
    

Upvotes: 0

Related Questions