Handle placeholderData with react-query
Unanswered
American black bear posted this in #help-forum
American black bearOP
Hey folks, I have a question and two issues regaring tanstack query I'd like to address
The first issue occurs when I use
The second issue is related to
Any suggestions or solutions would be greatly appreciated!
The hydration issue:
Error: Hydration failed because the initial UI does not match what was rendered on the server.
See more info here: https://nextjs.org/docs/messages/react-hydration-error
Expected server HTML to contain a matching <img> in <div>.
<img>
The first issue occurs when I use
placeholderData: prev => prev and have only one product. When I delete the product, it still appears on the screen instead of being removed. However, if I refresh the page, the product disappears. This issue doesn't occur when there are more than one product. my idea is to avoid showing a loading state on the screen every time I delete a product, as this triggers the API call and re-executes the queryThe second issue is related to
isLoading. When I refresh the page, I have a hydration issue. This problem doesn’t occur if I replace isLoading with isPending. However, using isPending causes a different issue where it stays in the loading state forever when I delete all products in the cart.Any suggestions or solutions would be greatly appreciated!
const {data, isLoading} = useQuery({
queryKey: [QUERY_KEYS.CALCULATE_PURCHASE, order?.items],
queryFn: async () =>
await calculateProducts({
payload: {
items: ProductService.toAPI(order?.tickets),
},
}),
enabled: !isEmpty(order?.items),
placeholderData: (previousData) => {
return previousData;
},
});
...
if (isLoading) return <PreLoader />;
return (
<div className="w-full flex-1 flex flex-col gap-4 p-4 overflow-y-auto">
{isEmpty(data?.items) ? (
<div className="w-full flex-1 text-center flex flex-col gap-3 items-center justify-center">
<ProductIcon className="size-6 text-blue-900 mx-auto" />
<h2 className="font-medium text-blue-900">{t('emptyCartTitle')}.</h2>
<p className="font-medium text-blue-900 text-xs">{t('emptyCartDescription')}</p>
</div>
) : (
data?.items?.map((product) => <ProductItem key={product?.id} product={product} />)
)}
</div>The hydration issue:
Error: Hydration failed because the initial UI does not match what was rendered on the server.
See more info here: https://nextjs.org/docs/messages/react-hydration-error
Expected server HTML to contain a matching <img> in <div>.
<img>