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?
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With