Search code examples
javascriptreactjsreduxreact-reduxmiddleware

Unhandled Rejection (TypeError): Cannot read property 'map' of undefined


I get the object from developers.themoviedb.org, but really dissapoint what wrong.
The object is sent to the browser, but I do not understand how to throw it to me.
I'm confused, need help
If in middleware i write let arr = JSON.parse(response).results; also an error:

Unexpected token o in JSON at position 1

response with object in browser

data.service.js

export const getData = (url) => new Promise((resolve, reject) => {
const request = new XMLHttpRequest();
request.open('GET', url);
request.onload = () =>
    (request.status === 200) ?
        resolve(JSON.parse(request.response).results) :
        reject(Error(request.statusText))
  request.onerror = (err) => reject(err)
  request.send();
});

movies.middleware.js

export const moviesMiddleware = store => next => action => {
if (action.type === FETCH_MOVIES_START) {
    getData(popularMovies).then((response) => {
        let arr = response.results;
        let movies = arr.map((item) => {
           return new MovieEntity(item);
        });
        let data = movies;
        store.dispatch({
            type: FETCH_MOVIES_SUCCESS,
            payload: data
        });
    });
  }
  return next(action);
}

movies.action.js

export function fetchMovies() {
return {
    type: FETCH_MOVIES_START
 }
}

Solution

  • Your data is already an object. No need to parse it. And every time before parsing check the typeOf the param is string or not. ------EDIT-----

    Also Try:

      resolve(
       if(typeOf(request.response)=='string')
        JSON.parse(request.response).results 
       else request.response.results
       )
    

    in movies.middleware.js change as below

    export const moviesMiddleware = store => next => action => {
    if (action.type === FETCH_MOVIES_START) {
        getData(popularMovies).then((response) => {
            let arr = response;
            let movies = arr.map((item) => {
               return new MovieEntity(item);
            });
            let data = movies;
            store.dispatch({
                type: FETCH_MOVIES_SUCCESS,
                payload: data
            });
        });
      }
      return next(action);
    }
    

    The thing is you are resolving promise with request.response.results and again in then you have accessed it the same way response.result either return request.response or change accessing as above response .