error TypeError: Cannot convert undefined or null to object

5.9k views Asked by At

i have this error with axios, the json load fine, but its a problem with the render

enter image description here

actions.js:

export const getUser = (callback)=>{
    return function(dispatch){
        dispatch({type: 'FETCH_GET_USER_REQUEST'});
        axios.get('https://jsonplaceholder.typicode.com/users')
        .then((response)=>{
            dispatch({type:'FETCH_GET_USER_SUCCES', payload:response.data});
            if (typeof callback === 'function') {
                callback(null, response.data)
            }
        })
    } 
}

reducerUser.js

export const getUserReducer = (state=[], action) =>{
    switch(action.type){
        case 'FETCH_GET_USER_REQUEST':
            return state;
        case 'FETCH_GET_USER_FAILURE':
            return state;   
        case 'FETCH_GET_USER_SUCCES':
            return [...action.payload.data];
        default:
            return state;
    }
}

container.jsx

class GetUserContainer extends Component{
    componentDidMount(){
        this.props.getUser();
    }
    render(){
        return(
            <GetUserComponent allUser={this.props.allUser} />
        )   
    }
}
function mapStateToProps(store){
        return{
            allUser:store.allUser
        }
}
function matchDispatchToProps(dispatch){
    return bindActionCreators({
        getUser:getUser
    }, dispatch)
}

store.js

 const store = createStore(
 reducers,
   applyMiddleware(thunk,  logger())
);
2

There are 2 answers

0
zlwaterfield On BEST ANSWER

Looking at your console output your, your issue is most likely in your reducer when the FETCH_GET_USER_SUCCES action is hit.

You are returning this: [...action.payload.data];. Try logging your payload, there may not be a data object on the payload hence the converting undefined or null to object error. I am betting you just need to return: [...action.payload];

0
ArneHugo On

From the error stack you can see the error is called from getUserReducer in your code, and then in _toConsumableArray which is a helper method created by babel when transpiling spread operator to es5.

Like @ಠ_ಠ said hinted at, you get the error because action.payload.data is not an object, in which case applying the spread operator will fail. ([...action.payload.data])