Redux thunk and imperative actions

For most part, React is declarative. But there are times when we have to use imperative methods. This is quite common in React native. In React native, after an API call, we may use imperative methods for notifications or navigation. So, how do we handle this? Below is a code snippet of an action using redux-thunk.

export function callApi() {
  return dispatch => {
    dispatch({ type: ActionTypes.CallApiPending });
    return axios.get()
    .then(response => {
      dispatch({ type: ActionTypes.CallApiFulfilled });
    })
    .catch(error => {
      dispatch({ type: ActionTypes.CallApiRejected });
    });
  };
}

In the above code, we call an API. If the API succeeds, we dispatch fulfilled action. Else, we dispatch a rejected action.

Usually, an event handler dispatches the callApi function.

handlePress() {
  this.props.callApi();
}

Let us say, we want to display an error message using the Alert API if there is an unknown error.

this.props.callApi();
// if successful
Alert.alert(title, error);

Sometimes, we want to navigate.

this.props.callApi()
// if successful  
this.props.navigation.navigate('SomeScreen');

Thankfully, these sort of imperative code blocks are rare in React. The usual way of sending all of these data to redux global state works quite well. But in the rare case of writing imperative code, callbacks work quite well.

export function callApi(callback) {
  return dispatch => {
    dispatch({ type: ActionTypes.CallApiPending });
    return axios.get()
    .then(response => {
      dispatch({ type: ActionTypes.CallApiFulfilled });
      callback();
    })
    .catch(error => {
      dispatch({ type: ActionTypes.CallApiRejected });
    });
  };
}

Pass the callback as a parameter to the action creator. And when you call the function, pass in the callback function like so.

this.props.callApi(() => {
  Alert.alert('Some message', 'title');
});

I have a code sample in CodeSandbox. As an added bonus, the code sample also has scaffolding code for setting up Redux in your React apps.

Related Posts

Leave a Reply

Your email address will not be published.