Search code examples
javascriptreactjsreduxdispatchaxios

error TypeError: Cannot convert undefined or null to object


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())
);

Solution

  • 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];