Redux Reducer => Cannot convert undefined or null to object

so I have a pretty odd error and I'm not sure why or how to fixit.

Uncaught TypeError: Cannot convert undefined or null to object

so what is wrong in here? I have tried to add the default state directly into the reducer how I saw other answers regarding this error but didn't worked for me.

Action:

export const createProfile = profileValues => async dispatch => {
  const response = await profileApi.post('/profileApi', profileValues);

  dispatch({ type: CREATE_PROFILE, payload: response.data });
};

Reducer:

const initialState = {
    values: {}
  };
  
  export default function(state = initialState, action) {
    switch (action.type) {
      case CREATE_PROFILE:
        return { ...state, [action.payload.id]: action.payload };
      default:
        return state;
    }
  }

Component:

const Profile = (props) => {

    useEffect(() => (props.createProfile()))

    return (
        'Return'
    );
};

const mapStateToProps = state => {
    return { profile: Object.values(state.profile) };
  };
  
  export default connect(
    mapStateToProps,
    { createProfile }
  )(Profile);

Solution 1:

Object.values() can't convert null or undefined to an object with properties it can extract.

Before the API returns, the mapStateToProps selector tries to get the values of state.profile, which is undefined:

const mapStateToProps = state => {
  return { profile: Object.values(state.profile) };
};

Set the initial value of the profile as an empty object:

const initialState = {
  values: {
    profile: {}
  }
};

Or use a fallback value - {} at the selector's level:

return { profile: Object.values(state.profile ?? {}) };