What is the best way to initialize a value asynchronously for React context API in the latest version of NextJS, version

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?

Answer №1

If you want to enhance your functionality, consider utilizing the getInitialProps method. For instance,

BasketContextProvider.getInitialProps = async (ctx: NextPageContext) => {
  const data = await fetchDataFromServer();
  return { data }
}

const BasketContext = createContext<any>([]);

export async function BasketContextProvider({ children, data }: {children:React.ReactNode; data: any}) {
  return <BasketContext.Provider value={data}>{children}</BasketContext.Provider>;
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Eliminate items from a list that have duplicate properties

I have a collection of objects, each with a unique NAME property. However, there are duplicates in the collection where some objects share the same NAME. const arr = [ {name: "x", place: "a", age: "13" }, {name: "x", place: "b", age: "14" }, { ...

What is the best way to send serverside parameters from ASP.Core to React?

After setting up a React/Typescript project using dotnet new "ASP.NET Core with React.js", I encountered the following setup in my index.cshtml: <div id="react-app"></div> @section scripts { <script src="~/dist/main.js" asp-append-versi ...

Delete the item along with its associated data from the local storage upon clicking on an icon

I'm currently working on a To-Do List and facing an issue while trying to delete an item upon clicking a trash bin icon. image The problem I'm encountering is that only one data point is removed from local storage when the icon is clicked. If I ...

Menu with options labeled using IDs in FluentUI/react-northstar

I'm currently working on creating a dropdown menu using the FluentUI/react-northstar Dropdown component. The issue I'm facing is that the 'items' prop for this component only accepts a 'string[]' for the names to be displayed ...

Converting large JSON data (approximately 100MB) into an Excel file using JavaScript

As a beginner in the realm of REST technology, I find myself navigating through a JSON response received from a server and showcasing the data on the client side. Currently, I am faced with handling approximately 22MB of JSON data that needs to be exporte ...

Where is the appropriate location to incorporate Vue.config.devtools = true?

I am interested in utilizing the Vue.js devtools, but I am uncertain about how to enable them. It seems like I need to include Vue.config.devtools = true after Vue has been loaded. However, it appears that Vue is loaded within a minified index.html file l ...

The data that was received on the Express backend appears to have been altered from how it was originally sent from the React frontend

I am facing an issue while attempting to send a post request from my React front end to my Express back end. The object I am trying to receive is showing up as the key of another object with an empty string value. Below is my onSubmit React function: han ...

Working with AngularJS: Implementing a Service in a Controller

A service has been developed in AngularJS, but it is not being utilized in the controller. Service.js var appService = angular.module("appService", []); appService.service("bddService", function() { var bdds = bdd; this.getBdds = function(){ ...

Encountering the "undefined error in cypress" when using (void 0)

Here is a scenario I am working on: before(()=>{ cy.fixture('example').then(function (data) { this.data = data; }) cy.visit("http://127.0.0.1:3000/"); cy.contains("Connect Wallet").click(); cy.cont ...

Leveraging Next.js for "client-side rendering" in React Encapsulations

My dilemma involves a component housing content crucial for SEO optimization. Here is an excerpt from my code: <AnimatedElement className="flex flex-col justify-start items-center gap-4 w-full" duration={500}> <h2 class ...

Issue with Angular UI-Router nested views: Content not displaying

I'm attempting to incorporate nested views for a webpage using angular ui-router. I have set up the state definitions according to various tutorials, but I am unable to display any content in the child views. Surprisingly, there are no errors showing ...

Locate the position of the cursor within a rectangular shape

I'm struggling to determine the location of a cursor within a rectangle, specifically which part (one of 4 triangles) it is in. This visual representation helps me grasp it better than any explanation I can come up with :s Working in javascript (whe ...

Typescript - Conditional imports

When working with the moment-timezone module, one issue that arises is receiving a warning if it is included multiple times. In my specific case, I have a module that necessitates the use of this timezone functionality. Since I am unsure whether or not the ...

Encountering a 400 Error while connecting to an API in Nextjs with the React Dropzone

I utilized the react-dropzone-uploader.js plugin to facilitate file uploads. However, upon making a fetch request to the API, I encountered a 400 Error. I have been unable to pinpoint a solution, but suspect it may be related to the getUploadParams funct ...

Personalized ornamentation using TypeScript

Is there a way to access the variables of the class when using a decorator? @ExampleDecorator() export class UserController { private userData: string = "example"; } export const ExampleDecorator = (config: IConfigSettings) => (target: Object) =&g ...

Looking to implement pagination on a table using Material UI within a React project?

I'm in the process of designing a table to display data. I would like to incorporate pagination similar to the one shown in the image provided, with numbers on the left-hand side and "Results per page" on the right-hand side in the footer. ...

Is it unorthodox to utilize constructor instances as prototypes in "WebGL - Up and Running"?

In the book "WebGL - Up and Running," a unique custom geometry is created in a rather straightforward manner. However, what caught my attention was the penultimate line of code. Here's how it looked: Saturn.Rings = function ( innerRadius, outerRadius ...

Dealing with Koa-router and handling POST requests

I am facing an issue handling POST requests in my koa-router. Despite using koa-bodyparser, I am unable to receive any data sent through my form. My template engine is Jade. router.js: var jade = require('jade'); var router = require('koa- ...

What is the process for inserting a new element into an array and then verifying its existence within the array?

I'm currently working on a get request to retrieve data from my database and display it on my website. One of my goals is to dynamically update the state when a new chat is created, rather than refreshing the entire screen every time. Whenever a new ...

Leveraging Jquery to add an element or text in front of the initial instance of a different element

Here is a sample of my xml code: <entry> <br> <abc></abc> <xyz></xyz> <example></example> <example></example> <example></example> </entry> <entry> <br> <abc>&l ...