Vidly calls to function in httpService.js to interact with MongoDB

In the vidly app, we are asked to replace the fake movie and genre services with services to connect to a MongoDB running on our machine. In all of Mosh’s examples, he simply returns the service all like so:

export function getGenres() { return httpService.get(apiEndpoint + ‘/genres’); }

But what if you wanted to do something like add an additional genre to what is returned or maybe you wanted to return just a subset containing only some of the fields that are returned (which seems like a life-like situation).

When I try to do something like:

export async function getGenres() {
const addedGenre = { _id: “123456”, name: “Silly” };
let { data } = await httpService.get(apiEndpoint + ‘/genres’);
const genres = [addedGenre, …data];
return genres;
}

I get the following error (in the file calling getGenres() )

Unhandled Rejection (TypeError): genres1 is not iterable

The call is being made in movies.jsx

async componentDidMount() {
    const defaultAllGenres = { _id: "", name: "All Genres" };
    const { data: genres1 } = await getGenres();
    const genres = [defaultAllGenres, ...genres1];

Can this be accomplished and if so, how?

I think your “genres1” variable is probably null.

The following line in componentDidMount() method of “movies.js” is expecting an object with a “data” property.

const { data: genres1 } = await getGenres();

You could either re-write this line, or change your modified getGenres() function to return an object with a “data” property as expected:

export async function getGenres() {

  // instead of: return genres;
  return { data: genres };
}

Just returning the data part of the returned object does work. What I am trying to do is take that data portion and iterate over it to send back a subset or different object based on what is returned. The error that I am getting is that “data” is not “iterable” in this function, but works just fine if I return the “data” as a whole.

Hey mogul,

I am also stuck with same issue.
Did you find the solution, why is it happening?

The reason behind getting “data” is not “iterable” because an async function always return a promise. If the return value of an async function is not explicitly a promise, it will be implicitly wrapped in a promise.

Source: async function - JavaScript | MDN