I have three tables in the backend, restaurants, categories and dishes, a restaurant can have several categories, and a category can have several dishes
I made the endpoints with Python/Django, AND IT’S WORKING OK, I tested them with postman
Basically, in the React frontend I’m loading the data in the redux/toolkit state
I want to build one object that has it all, the restaurant, its categories, and for each category, its dishes
It all starts with one restaurant
I load the restaurant => I load its categories => for each category I load its dishes.
I expect that in the nested .thens, I will be receiving them, but in the third step, the dishes, it fails, its “.then” gets undefined
export const fetchMenu = createAsyncThunk(
"menu/fetchMenu",
async (restaurantId) => {
var restaurant = null;
var menuPromise = new Promise(function (resolve, reject) {
loadRestaurantFromApi(restaurantId)
.then((dataR) => {
restaurant = dataR; // load restaurant’s data
return loadCategoriesFromApi(restaurant.id); // read its categories
})
.then((dataC) => { // If they were read correctly, then load them in the general object
restaurant["categories"] = dataC;
restaurant["categories"].forEach( // It is generating several return loadDishesFromApi…
(category) => {
return loadDishesFromApi(category.id); // for each category, read its dishes
}
);
})
.then((dataD) => {
// HERE, DATAD IS UNDEFINED!!! WHY?, it’s inside a .then!!!
// Load dishes in the right place…
resolve(restaurant);
})
.catch((error) => {
console.log("fetchMenu:: error: ", error);
reject(error);
});
});
return menuPromise;
}
);
Each load...FromApi are like this:
export async function loadDishesFromApi(categoryId) {
try {
const response = await axiosInstance.get(
`/dishes_list_all/` + categoryId // the endpoint in Django is dishes_list_all
); // It works OK
return response.data;
} catch (error) {
alert(`loadDishesFromApi failed: ${error}`);
return error.message;
}
}
The axiosInstance is like:
const axiosInstance = axios.create({
baseURL: "http://127.0.0.1:8000/api/v1/",
});
The view.py for loadDishesFromAPI is like:
@api_view(["GET"])
def dishes_list_all(request, category_id):
dishes = Dish.objects.filter(category=category_id)
serializer = Dish_Serializer(dishes, many=True)
return Response(serializer.data)
And it's corresponding path is:
path("dishes_list_all/<int:category_id>", dishes_list_all),
Why does it fail in the last step, what could I be doing wrong here?
(A solution with a read that reads it all from the backend in one step (using the foreign keys) is also welcomed)
Thanks in advance
Rafael