Search code examples
javascriptreactjsredux

React, Redux: Uncaught TypeError: Cannot read properties of undefined (reading 'region')


I am fetching data (an object) into a redux state and showing into textarea when user clicks on edit:

const regionData = useSelector((state) => state.myReducer.userDetailList.region);

but first time it gives me below error:

Uncaught TypeError: Cannot read properties of undefined (reading 'region')

also this error occurred when i changed code as per eslint suggestion:

i.e. 
Use an object spread instead of `Object.assign` eg: `{ ...foo }`

Old Code:

return Object.assign({}, state, {
    userDetailList: {
        region: action.userDetailsPayload.region,
    },
});

New Code:

 const userDetailList = {
     region: action.userDetailsPayload.region,
 };

 return { ...state, ...userDetailList };

As a result userDetailList showing as BLANK in Chrome redux-devtool. its working with old code (Object.assign)

I am new to react and redux, so any help is much appreciated. Thanks!


Solution

  • I had a promblem same this one. Finally I've found out that if I use term "Reducer" or "State" at the end of state's name or reducer's name that are witten by me, my code runs with error

    Uncaught TypeError: Cannot read properties of undefined (reading 'result_201')

    my reducer:

        export function netInfoRecordReducer (
        state = initialStateNetInfoRecord,
        action : Actions
      ) : NetInfoRecordState {
        switch (action.type) {
          case SET_NET_INFO_RECORD: {
            if ( action.payload.RESULT === "SUCCESS") {
              return {
                ...state,
                result_201: action.payload.RESULT_CONTENT,
              };
            }
            return state;
          }
          default:
            return state;
        }
      }
    

    and my index.tsx file for defining CobineReducer and RoutState:

    export default combineReducers({
      netInfoRecordReducer: netInfoRecordReducer,
    });
    
    export interface RootState {
      netInfoRecordState: NetInfoRecordState;
    }
    

    it runs with that error when I want acceess to the state in another file:

        const netInfoRecord = useAppSelector( (state) => 
            state.netInfoRecord.result_201);
        console.log(netInfoRecord);
    

    but if I remove "State" and "Reducer" term and change my index.tsx file to :

        export default combineReducers({
          netInfoRecord: netInfoRecordReducer,
        });
    
        export interface RootState {
         netInfoRecord: NetInfoRecordState;
        }
    

    it works now ! :)