phongyewtong
phongyewtong

Reputation: 5309

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, ????)

Upvotes: 0

Views: 1489

Answers (3)

jonny133
jonny133

Reputation: 126

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))

Upvotes: 2

phry
phry

Reputation: 44136

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.

Upvotes: 1

Linda Paiste
Linda Paiste

Reputation: 42218

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}));

Upvotes: 2

Related Questions