1

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?

Aldo
  • 1,199
  • 12
  • 19

2 Answers2

2

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); }
  }
}
Matt Carlotta
  • 18,972
  • 4
  • 39
  • 51
  • reduced the boilerplate, nice answer. – Aldo Oct 15 '18 at 00:35
  • Just a small heads up: If you ever plan on pushing this to production, then you'll need a better way of defining your `API` url. Hard coding `http://localhost:8080` in the `fetch` request won't work in production! – Matt Carlotta Oct 15 '18 at 00:45
  • Sure. I tried to use a process.env, however the react-admin and create-react-app does not use the .env as a common node application. When come the time to release it to production I am gonna look for a proper solution. Thanks. – Aldo Oct 15 '18 at 12:03
0

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;
        });
    }
    
Aldo
  • 1,199
  • 12
  • 19