A
A
AltaiR2019-11-22 09:40:57
React
AltaiR, 2019-11-22 09:40:57

Is it correct to pass callback to middleware?

Is it a good idea to pass callbacks to middleware and call them there, or is it more correct to do it in componentDidUpdate ?

// component.js
class LoginPage extends Component {

  // ...

  onSubmit = (values) => {
    const { dispatch } = this.props;

    dispatch(
      login(
        values,
        (token) => localStorage.setItem('accessToken', token),  // success callback, который будет вызван в middleware
        (error) => console.log(error.message) // error callback, который будет вызван в middleware
      )
    );
  }

}

// actions.js
function loginAction(payload, onSuccess, onError) {
  return {
    type: LOGIN,
    payload,
    onSuccess,
    onError,
  }
}

// middleware.js
function handleLogin(action) {
  const { payload, onSuccess, onError } = action;
  try {
    // login...
    onSuccess(token);
  } catch(error) {
    onError(error);
  }
}

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question