Ashraf Ali
Ashraf Ali

Reputation: 11

React-Redux action.payload is undefined

I'm a beginner in Redux. I'm trying to GET a users list, but when I console.log(action.payload) in reducer function it is showing undefined.

const URL = 'http://localhost:3001/api/'

export function fetchUsers() {
  return (dispatch) => {
    dispatch(fetchUserRequest());
    return axios.get(`${URL}userdata`)
      .then(response => response.json())
      .then(userlist => fetchedUsersSuccessfully(userlist.data))

  }
}

export function fetchUserRequest() {
  return {
    type: 'FETCH_REQUEST',
  }
}
export function fetchedUsersSuccessfully(users) {
  return {
    type: 'FETCH_USERS',
    payload: users
  }
}

This is my reducer

export function users(state = InitialState, action) {
  console.log(action.payload)
  switch (action.type) {
    case FETCH_USERS:
      return [...state, action.payload]
    default:
      return state;
  }

}

Upvotes: 1

Views: 9696

Answers (3)

TAHA SULTAN TEMURI
TAHA SULTAN TEMURI

Reputation: 5191

In my case the api was returning a response into data and I was checking into a variable , Fix was to directly use Object of your Response model in api call.

Action:

getPaidMarketingOnlyPiadMarketingDataSuccess: (state, action: PayloadAction<MarketingOnlyPaidMarketingData>) => {
  debugger;
  state.paidMarketingOnlyData = action.payload;
  state.loading = false;
}



//OLD

  dispatch(paidMarketingSlice.actions.getPaidMarketingOnlyPiadMarketingDataSuccess(data.marketingOnlyPaidMarketingData));




//OLD 

 const getPaidMarketingOverviewData = (params: 
 GetPaidMarketingOverviewDataRequest) =>
 vennFlowApi.get<{ marketingOnlyPaidMarketingData: 
 MarketingOnlyPaidMarketingData}>(
 '/MarketingOnlyPaidMarketing/MarketingOnlyPaidMarketing',
 {
   params,
 },
 );



 //WORKING 
  const getPaidMarketingOverviewData = (params: 
  GetPaidMarketingOverviewDataRequest) =>
  vennFlowApi.get< MarketingOnlyPaidMarketingData>(
  '/MarketingOnlyPaidMarketing/MarketingOnlyPaidMarketing',
  {
    params,
  },
  );


 dispatch(paidMarketingSlice.actions.getPaidMarketingOnlyPiadMarketingDataSuccess(data));

Upvotes: 0

Kevin
Kevin

Reputation: 961

When a store is created, an "INIT" action is dispatched. So all reducer return their initial value. By this your initial state tree is populated. So if you are getting the undefined error, it can be due to @@INIT actions which has no payload.

Plus, whenever you dispatch an action, all of your reducers are called, your fetchUserRequest action has no payload, so you get undefined error.

Upvotes: 1

rodgobbi
rodgobbi

Reputation: 1522

You've just forgot to dispatch the success action just like you did with the first one. The correct dispatching should be like:

.then(response => response.json()).then(userlist => dispatch(fetchedUsersSuccessfully(userlist.data)))

Upvotes: 2

Related Questions