Home > Enterprise >  React JS JSX, can't understand the usefulness of a callback passed in param inside a statless f
React JS JSX, can't understand the usefulness of a callback passed in param inside a statless f

Time:03-30

I'm working on REACT JS project with react router 6. I'm trying to use React Context to handle authentication.

In this example :

const fakeAuthProvider = {
  isAuthenticated: false,
  signin(callback) {
    fakeAuthProvider.isAuthenticated = true;
    setTimeout(callback, 100); // fake async
  },
  signout(callback) {
    fakeAuthProvider.isAuthenticated = false;
    setTimeout(callback, 100);
  },
};

export { fakeAuthProvider };

  let signin = (newUser, callback) => {
    return fakeAuthProvider.signin(() => {
      setUser(newUser);
      callback(); // why the passed callback is called here ?
    });
  };

  let signout = (callback) => {
    return fakeAuthProvider.signout(() => {
      setUser(null);
      callback(); // why the passed callback is called here ?
    });
  };

I don't understand why the callback is called over there knowing that it is not declared somewhere ?

I will be greatefull if someone explain to me

CodePudding user response:

The callback you are referring to is not the callback you are passing in the fakeAuthProvider object method.

Calling it there is meant for when the user is signed in or signed out and something needs to be done, pass that in as a callback.

By way of example, if you want to show toast message that the user has logged in, you could pass a function in place of signinCallback that will get executed as soon as the user signs in.

Take a look at the following code.

const fakeAuthProvider = {
  isAuthenticated: false,
  fakeAuthSignin(fakeAuthCallback) {
    fakeAuthProvider.isAuthenticated = true;
    setTimeout(fakeAuthCallback, 100); // fake async
  },
  fakeAuthSignout(fakeAuthCallback) {
    fakeAuthProvider.isAuthenticated = false;
    setTimeout(fakeAuthCallback, 100);
  },
};

export { fakeAuthProvider };

let signin = (newUser, signinCallback) => {
  // the arrow function that you are passing in 'fakeAuthProvider.fakeAuthSignin' is 'fakeAuthCallback'
  return fakeAuthProvider.fakeAuthSignin(() => {
    setUser(newUser);
    signinCallback(); // this is a callback which you will pass in 'signin' function. It will get executed once user is authorized.
  });
};

let signout = (signoutCallback) => {
  // the arrow function that you are passing in 'fakeAuthProvider.fakeAuthSignout' is fakeAuthCallback
  return fakeAuthProvider.fakeAuthSignout(() => {
    setUser(null);
    signoutCallback(); // this is a callback which you will pass in 'signout' function
  });
};

  • Related