Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
477 views
in Technique[技术] by (71.8m points)

javascript - 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);
question from:https://stackoverflow.com/questions/65937419/redux-reducer-cannot-convert-undefined-or-null-to-object

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Object.values() can 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: {}
  }
};

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

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...