0

The goal here is to call an action from my component and get the single object from the reducer, and with that object, I will load my form.

Redux is working, but its returning the single object that I want as my whole state

My component:

const dispatch = useDispatch()

const rewardFromRedux = dispatch(getProductForUpdateAction('reward', rewardIdForUpdate))

// After getting the information from redux, I will load my component state like this:
const [title, setTitle] = useState(rewardFromRedux ? rewardFromRedux.title : '')
const [about, setAbout] = useState(rewardFromRedux ? rewardFromRedux.about : '')

My action:

// receives a product type (survey, reward) and the productId
// and call action to get the product from the reducer

export function getProductForUpdate(productType, productId) {
  switch (productType) {
    case 'reward':
      return {
        type: actions.GET_REWARD_FOR_UPDATE,
        payload: productId,
      }

    default:
      return null
  }
}

My reducer:

case GET_REWARD_FOR_UPDATE:
   return produce(state, draft => {
     const rewardIndex = draft.campaign_products.reward.rewards.findIndex(
       p => p.uuid === action.payload,
     )
     if (rewardIndex >= 0) {

       // the problem is here, is returning the item that I want but as my whole state
       // state.campaign_products.reward.rewards is my array of reward objects

       return state.campaign_products.reward.rewards[rewardIndex]
     }
   })

How can I return only the object that I want?

fjurr
  • 541
  • 2
  • 8
  • 23

1 Answers1

1

Create then use a selector.

Selector

export const getRewardByIndex = (rewardIndex) => (state) => {
  return state.campaign_products.reward.rewards[rewardIndex];
};

In your component

import { useSelector } from 'react-redux';

const someIndex = 0;
const reward = useSelector(getRewardByIndex(someIndex));
James
  • 11
  • 1