Home > other >  How do you use Redux useDispatch to pass in values?
How do you use Redux useDispatch to pass in values?

Time:01-02

How do I set up actions in a @reduxjs/toolkit slice to pass data through the action?

Here is the slice:

import { createSlice } from '@reduxjs/toolkit'

export tempSlice = createSlice({
  name: "temp",
  initialState: {
    value: 1
  },
  reducers: {
    updateTemp: (data) => {
      console.log(data)
    }
  }
})

export const { updateTemp } = tempSlice.actions

export default tempSlice.reducer

In a react component, this doesn't work. I keep getting errors saying it's expecting 0 arguments.

useDispatch(updateTemp(newData))

CodePudding user response:

Actions created via a state slice accept a single argument object that will be placed on the action's payload property. The reducer function takes two arguments, the previous state and the dispatched action object. useDispatch is a React hook and doesn't take any arguments, it returns the dispatch function that is used to dispatch actions.

export tempSlice = createSlice({
  name: "temp",
  initialState: {
    value: 1
  },
  reducers: {
    updateTemp: (state, action) => {
      console.log(action.payload);
      ...
    }
  }
})
const dispatch = useDispatch(); // <-- no arguments
...
dispatch(updateTemp(newData));  // <-- newData is action payload
  • Related