i am trying to generate an array of movies which is working correctly and the "result" which is being consoled has the genres id
and the getGenres function has all the genres with id
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.