sajad torkamani

In a nutshell

createAction is a helper function that lets you define a Redux action type and the action creator in one step. You can use it in the following way:

import { createAction, nanoid } from '@reduxjs/toolkit'

const addTodo = createAction('todos/add', function prepare(text) {
  return {
    payload: {
      text,
      id: nanoid(),
      createdAt: new Date().toISOString(),
    },
  }
})

console.log(addTodo('Write more docs'))
/**
 * {
 *   type: 'todos/add',
 *   payload: {
 *     text: 'Write more docs',
 *     id: '4AJvwMSWEHCchcWYga3dj',
 *     createdAt: '2019-10-03T07:53:36.581Z'
 *   }
 * }
 **/

Notice how the first argument to createAction (todos/add) becomes the type of the generated action.

Without the helper function, we’d have to do something like:

import { createAction, nanoid } from '@reduxjs/toolkit'

const ADD_TODO = 'todos/add'

function addTodo(text) {
  return {
    type: ADD_TODO,
    payload: {
      text,
      id: nanoid(),
      createdAt: new Date().toISOString(),
    },
  }
}

Access action type with toString()

You can access the generated action type like so:

import { createAction, nanoid } from '@reduxjs/toolkit'

const addTodo = createAction('todos/add', function prepare(text) {
  return {
    payload: {
      text,
      id: nanoid(),
      createdAt: new Date().toISOString(),
    },
  }
})

console.log(addTodo.toString()) // 'todos/add'

Sources

Tagged: Redux