0

i am trying to generate an array of movies which is working correctly and the "result" which is being consoled has the genres idHere is the consoled data in result and the getGenres function has all the genres with id Genres data why is genres empty in when movies array is being created.

export const getGenres = createAsyncThunk("netflix/genres", async () => {
  const {
    data: { genres },
  } = await axios.get(`${TMBD_BASE_URL}/genre/movie/list?api_key=${API_KEY}`);
  console.log(genres);
  return genres;
});
const netflixSlice = createSlice({
  name: "netflix",
  initialState,
  extraReducers: (builder) => {
    builder.addCase(getGenres.fulfilled, (state, action) => {
      state.genres = action.payload;
      state.genresLoaded = true;
    });
    builder.addCase(fetchMovies.fulfilled, (state, action) => {
      state.movies = action.payload;
    });
  },
});
export const fetchMovies = createAsyncThunk(
  "netflix/trending",
  async ({ type }, thunkAPI) => {
    const {
      netflix: { genres },
    } = thunkAPI.getState();
    return rawData(
      `${TMBD_BASE_URL}/trending/${type}/week?api_key=${API_KEY}`,
      genres,
      true
    );
  }
);
const rawData = async (api, genres, paging = false) => {
  const moviesArray = [];
  for (let i = 1; moviesArray.length < 60 && i < 10; i++) {
    try {
      const {
        data: { results },
      } = await axios.get(`${api}${paging ? `&page=${i}` : ""}`);

      createArrayfromRawdata(results, moviesArray, genres);
    } catch (error) {
      console.error(error);
    }
  }

  return moviesArray;
};
const createArrayfromRawdata = (array, moviesArray, genres) => {
  array.forEach((movie) => {
    const movieGenres = [];
    movie.genre_ids.forEach((genre) => {
      const name = genres.find(({ id }) => id === genre);
      if (name) movieGenres.push(name.name);
    });
    if (movie.backdrop_path)
      moviesArray.push({
        id: movie.id,
        name: movie?.original_name ? movie.original_name : movie.original_title,
        image: movie.backdrop_path,
        genres: movieGenres.slice(0, 3),
      });
  });
};

I am trying to get the genres according to the movie data and which matches the id of the genres.

Fam fas
  • 17
  • 3
  • It is likely that the genres array is empty because the `genres` variable in the `getGenres` function is not being populated correctly. The `axios.get` call is not returning the expected data, or it is not being handled correctly. Check the response data from the API and make sure it is being handled correctly in the `getGenres` function. – Omar Dieh Feb 05 '23 at 12:13

0 Answers0