createAction() Example

Let’s have a look at an example using the createAction function.

Here’s a complete example using the createAction() function:

const addRecipe = createAction(
  ADD_RECIPE,
  (title, description ) => (...args),
  { silent: true }
);

const addRecipeAsync = (title, description = '') => {
  const details = { ...args };

  return (dispatch) => {
    axios.post('/recipes', {
      data: JSON.stringify(details)
    })
    .then(response => dispatch(addRecipe(response.details))),
    .catch(error => dispatch(addRecipe(new Error(error))));
  }
};

In the example above, we first use createAction() to addRecipe. This automatically creates an object of type ADD_RECIPE with a title, description, and silent:true option.

const addRecipe = createAction(
  ADD_RECIPE,
  (title, description ) => (...args),
  { silent: true }
);

We then use the axios library to send a request to the server:

const details = { ...args };

return (dispatch) => {
  axios.post('/recipes', {
    data: JSON.stringify(details)
  })

We then use axios to determine whether to create a successful action or an Error one:

.then(response => dispatch(addRecipe(response.details))),
.catch(error => dispatch(addRecipe(new Error(error))));

In case of success, the following object will be dispatched:

{
  type: ADD_RECIPE,
  title: title,
  description: description,
  {silent: true} 
}

In case of error, the following object will be displayed:

{
  type: ADD_RECIPE,
  ERROR: error
}

Get hands-on with 1200+ tech skills courses.