Currently, I'm working on implementing the React context API in my NextJS e-commerce application to manage a user's shopping cart. The challenge I'm facing is how to retrieve the cart contents from MongoDB to initiate the cart context. This seems tricky because the context provider is located in a file labeled "use client."
I'm aiming for something along these lines:
'use client';
import { createContext, useState } from 'react';
const BasketContext = createContext<any>([]);
export async function BasketContextProvider({ children }: {children:React.ReactNode}) {
const value = await fetchCartContentsFromMongoDB();
return <BasketContext.Provider value={value}>{children}</BasketContext.Provider>;
}
The issue here is that client components cannot be marked as async. So, my question is: How can I utilize a provider to expose a value with an initial asynchronous setup?