1

The goal is to get to send an object from my form to my action. (no async)

I keep getting "Actions must be plain objects. Use custom middleware for async actions."

I have my action like this (I can console.log the productType and product,the data is coming to my action but I keep getting the console error mentioned above):

export function addProduct(productType, product) {
  switch (productType) {
    case 'survey':
      return {
        type: actions.ADD_SURVEY,
        payload: product,
      }

    case 'reward':
      return {
        type: actions.ADD_REWARD,
        payload: product,
      }

    default:
      return null
  }
}

In my component, I'm calling my action (data is the object from my form):

import { useDispatch } from 'react-redux'

 const dispatch = useDispatch()

function onSubmit(data) {
  const productType = 'reward'
  dispatch(addProductAction({ productType, data }))
}
fjurr
  • 541
  • 2
  • 8
  • 23

2 Answers2

3

When you dispatched an action, you passed an object to your action creator

dispatch(addProductAction({ productType, data }))

but your action creator takes 2 parameters, productType and product. Object you pass to your action creator is assigned to first parameter your action creator takes, i.e. productType.

Inside the action creator, you are using productType in switch statement. You expect it to be string but its an object. So your default case runs and null is returned from your action creator.

You can destructure the object passed to the action creator and then use productType in switch statement. Change your action creator as shown below

export function addProduct({productType, data}) {
  switch (productType) {
    case 'survey':
      return {
        type: actions.ADD_SURVEY,
        payload: data,
      }

    case 'reward':
      return {
        type: actions.ADD_REWARD,
        payload: data,
      }

    default:
      return null
  }
}

OR

you could just not pass an object to the action creator when dispatching an action

Change

dispatch(addProductAction({ productType, data }))

to

dispatch(addProductAction(productType, data))
Yousaf
  • 27,861
  • 6
  • 44
  • 69
1

You need to fire the dispatch inside your action creator. Not the other way around.

You can do something like this:

import store from './path/to/store'

const dispatch = store.dispatch

export function addProduct(productType, product) {
  switch (productType) {
    case 'survey':
      dispatch({ type: actions.ADD_SURVEY, payload: product })

    case 'reward':
      dispatch({ type: actions.ADD_REWARD, payload: product})

    default:
      return null
  }
}
import { addProduct } from './path/to/actions'

function onSubmit(data) {
  const productType = 'reward'
  addProduct(productType, data)
}

If you want to use the dispatch hook in your React component, you must pass a plain object like dispatch({ action: 'action', payload: data })

Thales
  • 346
  • 1
  • 5