import { useQueries, useQuery, useQueryClient } from '@tanstack/react-query' import { useState } from 'react' import { ApiError } from '../../api/ApiError' import getImage from '../../api/getImage' import getRecipeInfos from '../../api/getRecipeInfos' import { useAuth } from '../../auth' import RecipeCard from '../../components/recipe-card/RecipeCard' import classes from './recipes.module.css' const Recipes = () => { const [pageNumber, setPageNumber] = useState(0) const [pageSize, setPageSize] = useState(20) const { accessToken } = useAuth() const queryClient = useQueryClient() const { data, isPending, error } = useQuery( { queryKey: ['recipeInfos'], queryFn: ({ signal }) => getRecipeInfos({ abortSignal: signal, pageNumber, pageSize, accessToken }) }, queryClient ) const slugsAndImgUrls = useQueries({ queries: data !== undefined ? data.content.map(recipeInfoView => { return { enabled: recipeInfoView.mainImage !== null, queryKey: [ 'images', recipeInfoView.mainImage?.owner.username, recipeInfoView.mainImage?.filename ], queryFn: async ({ signal }: any) => { // any needed in the params const imgUrl = await getImage({ accessToken, signal, url: recipeInfoView.mainImage!.url }) return { slug: recipeInfoView.slug, imgUrl } } } }) : [] }) if (isPending) { return

Loading...

} else if (error) { if (error instanceof ApiError) { return (

ApiError: {error.status} {error.message}

) } else { return

Error: {error.message}

} } else { return ( <>

Recipes

{data.content.map(view => ( { return slugAndImgUrl !== undefined && slugAndImgUrl.slug === view.slug })?.data!.imgUrl ?? '' // hacky workaround. should pass a kind of child which loads its own data } mainImageAlt={view.mainImage?.alt ? view.mainImage.alt : undefined} starCount={view.starCount} isPublic={view.isPublic} /> ))}
) } } export default Recipes