'Adding a payload to createAction function using reduxjs/toolkit

How do i add a payload to createAction from the now function?

convert from this:

import { ADD_ARTICLE } from "../constants/actions-type"
import { createAction } from "@reduxjs/toolkit"
export function addArticle(payload) {
  return { type: ADD_ARTICLE, payload }
};

convert to this:

export const addArticle = createAction(ADD_ARTICLE, ????)


Solution 1:[1]

The second argument of createAction is a function which takes the arguments of your action creator and maps them to an object with the payload property. Since your action creator takes the whole payload as an argument, it's this:

export const addArticle = createAction(ADD_ARTICLE, payload => ({payload}));

Solution 2:[2]

You don't need to do anything. The result of createAction is an action creator function that accepts one argument and puts it on payload.

So export const addArticle = createAction(ADD_ARTICLE) does exactly what you want.

Solution 3:[3]

For TypeScript, adding a generic type to createAction hints the resulting action creator takes a payload of type PayloadType:

export const addArticle = createAction<PayloadType>(ADD_ARTICLE)

then for payload: PayloadType, you can

dispatch(addArticle(payload))

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Linda Paiste
Solution 2 phry
Solution 3 jonny133