Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you pass arguments to createAsyncThunk in redux toolkit?

So i'm new to redux-toolkit and I want to do something really simple. I want to send some data on a POST request via this helper function. so I tried this

export const submitPaymentToServer = createAsyncThunk(
    'data/fetchAll',
    async ({ name, data }) => {
        return fetch('/payments', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({
                name,
                data,
            }),
        })
            .then((res) => res.json())
            .then((res) => res)
    },
)

but when I call it like so

    dispatch(
        submitPaymentToServer({
            name,
            data,
        }),
    )

typescript complains saying I don't have the right number of arguments. so how am I suppose to pass args to this function? or what is the way to do this with toolkit?

like image 208
Red Baron Avatar asked Nov 08 '20 20:11

Red Baron


People also ask

Can I use redux-thunk with Redux toolkit?

The redux-thunk package is included in the Redux Toolkit ( @reduxjs/redux-toolkit ) package. To install @reduxjs/redux-toolkit or the standalone redux-thunk package use npm . The redux-thunk middleware allows for asynchronous logic when interacting with the Redux store.

How do you get Tostate in Redux toolkit?

export const create = (id) => { return async (dispatch, getState) => { const currentState= getState(). example; console. log(currentState) }; }; You can access the slice state using the above code.


1 Answers

This is what React-Redux says when you are using createAsyncThunk

You can only pass one argument to the thunk when you dispatch it. If you need to pass multiple values, pass them in a single object

So instead of

export const submitPaymentToServer = createAsyncThunk(
    'data/fetchAll',
    async ({ name, data }) => { // here you have two arguments
        return fetch('/payments', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({
                name,
                data,
            }),
        })
            .then((res) => res.json())
            .then((res) => res)
    },
)

You can only have one argument:

export const submitPaymentToServer = createAsyncThunk(
    'data/fetchAll',
    async (yourData) => {
        const {name, data} = yourData;
        return fetch('/payments', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({
                name,
                data,
            }),
        })
            .then((res) => res.json())
            .then((res) => res)
    },
)

Destructure your object inside the thunk call.

Reference: here

like image 126
Shiqi Avatar answered Sep 27 '22 20:09

Shiqi