Can you explain the process of accessing data from [[PromiseValue]] while utilizing React hooks?

My current challenge involves fetching data from an API and utilizing it in various components through the Context API.

The issue arises when I receive a response, but it's wrapped under a Promise.[[PromiseValue]]. How can I properly fetch this data to make it usable within my components?

import React,{useState, useEffect, createContext} from 'react';

export const ProductsContext = createContext();

export const ProductsProvider = props => {
    const [categories, setCategories] = useState({ categories: {} });
    const [products, setProducts] = useState({ products: {} });
    const [loading, setLoading] = useState(true);
    useEffect(() => {

        (async () => {
            const [categoriesResult, productsResult] = await Promise.all([fetch('/api/categories'), fetch('/api/products')]);
            setCategories(categoriesResult.json());
            setProducts(productsResult.json());
            setLoading(false);
          })(); 
        }, []);
    return (
        <ProductsContext.Provider value={ { products, categories, loading } }>
            {props.children}
        </ProductsContext.Provider>
    );
}

Upon attempting to access the data within the context, the response is successfully retrieved, although encapsulated in a [[PromiseValue]]

import React from 'react';
import ProductsContainer from './Products/ProductsContainer';
import {ProductsProvider} from './Products/ProductsContext';
const Page = () => (

    <>
      <Header/>
      <Banner/>
      <ProductsProvider>
        <ProductsContainer/>
      </ProductsProvider>
    </>

);

export default Page;


import React, { useContext } from 'react';
import { ProductsContext } from './ProductsContext';


const Products = () => {
    const {products, categories, loading} = useContext(ProductsContext);
    return (
        <div className="products">
            {
                console.log(products)
            }
        </div>
    ); 
};

export default Products;

The resulting response looks like this:

https://i.stack.imgur.com/GQQ0j.png

Answer №1

When using the .json() function with responses from the fetch method, it's important to note that it is asynchronous. This means that when you set your context state with setXXX(xxx.json()), you are actually setting it to a promise.

In order to access the resolved value within this promise, you should change your code to setXXX(await xxx.json()). By doing this, you will be able to access the array of data you are looking for within your functional component that is connected to the context.

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

What is the best way to obtain an up-to-date inventory of the properties that a component can receive?

Currently, I am utilizing the most recent version of material-ui and I am keen on discovering the acceptable props for a specific component, such as AppBar. While I found only 4 listed props in the Component API documentation available here, it seems tha ...

Display a loading splash screen prior to loading Next.js

I am working on a NextJS website and I'm looking to incorporate a Splash Screen that displays before the site is fully loaded. However, since the Splash Screen is included in the NextJS code, it ends up loading after NextJS has rendered on the server ...

Using NodeJS and ExpressJS to send the HTTP request response back to the client

After creating a website using Angular 2 and setting up node.js as the backend, I successfully established communication between the Angular client and the node.js server. From there, I managed to forward requests to another application via HTTP. My curren ...

What is the process of transferring data from one div to another div (table) using AngularJS?

In my quest to enhance my table with JSON data upon clicking the + icon, I am faced with two sections: Pick Stocks where stock names and prices (retrieved from data.json) need to be added to the table found in the Manage Portfolio section. First Section h ...

Enhancing Class Components with a different approach to styling rather than using makeStyles

I have come across examples that demonstrate how to utilize the makeStyles hook in order to style functional components in Material Design. However, since I am working with a class component, I am unable to use hooks. The code snippet often used for functi ...

No solution was found for implementing Airbnb TypeScript in React.js (Next.js) using ESLint

screenshot I encountered an issue where I couldn't locate the Airbnb typescript option in React JS (Next JS) within ESLint. Prior to this, I had installed Storybook and mistakenly clicked "yes" when prompted to migrate ESLint to Storybook. ...

When the onload event is triggered, the jscript function called var data is loaded, without any interruption in

I encountered an issue while trying to preview an image from a BBCode decoder. The code works fine, but I need the image to be inside an <a> href link, so that people can click on it and get the image source. Additionally, I want to display a message ...

Create a toggle effect similar to jQuery using JavaScript

Looking for pure JavaScript code to implement show/hide functionality similar to jQuery. Currently, I am using the following code: y=document.getElementById('regform').style.display; if (y == 'block'){ document.getElementById(&apo ...

Setting up a local development environment for AngularJS

I have been using the boilerplate https://github.com/node90/angular-starter as a foundation for my projects. However, I've noticed that the repository utilizes gulp to consolidate the js files in the 'app' folder into the 'public/js&apo ...

The addClass and removeClass functions seem to be malfunctioning

Hey everyone, this is my first time reaching out for help here. I looked through previous questions but couldn't find anything similar to my issue. I'm currently working on a corporate website using bootstrap3 in Brackets. I've been testing ...

JQuery UI Autocomplete: Results, Ctrl + A and Delete

I am currently designing a form that allows users to add members to a project. Only members with existing profiles in the system can be added. The form includes an input field for the member's name and a select box for their position, which is initial ...

As soon as I hit the submit button on my website form, the URL is automatically refreshed with the information I provided

I am a beginner when it comes to forms and recently copied and pasted this login snippet code: <div class="login-form-1"> <form id="login-form" class="text-left"> <div class="main-login-form"> <div class="login-group"> ...

Changing focus to 'DIV' element without JQuery using Javascript and Angular's ng-click event

Instructions for using an Angular directive to set focus on a "DIV" element when clicked <a href="#" class="skipToContent" ng-click="showContent()" title="skip-to-main-content">Skip To Main Content</a> <div class="getFocus" role="button" ...

"Triggering the jQuery mouseout event following a resize of an element

I'm currently trying to develop a dynamic shopping cart widget. The concept is to have a box that displays the number of items in your cart, and when you click on it, it expands to show a detailed view of the cart contents. I've successfully man ...

The issue of JQuery mobile customizing horizontal radio buttons failing to function on physical devices has been identified

Not long ago, I posed a query on Stackoverflow regarding the customization of horizontal jQuery-mobile radio buttons. You can find the original post by following this link How to customize horizontal jQuery-mobile radio buttons. A developer promptly respon ...

Angular state correctly maps to the controller but is not reflected in the HTML

I'm currently in the process of setting up a basic Angular application, something I've done many times before. I have defined a home state and another state for a note-taking app, but I am facing an issue where neither state is displaying or inje ...

How do I retrieve the music events for each user in Strapi 4?

I am currently working with strapi 4 and nextjs. Within the app, each user has their own music events stored in strapi that they should be able to add and retrieve. However, I am encountering difficulties when trying to retrieve each user's music ev ...

Will it function properly if it is (NULL)?

Here's the code snippet I'm currently using: <html> <head> <link type="text/css" rel="stylesheet" href="html.css" /> <script type="text/javascript"> function getName() { if(name) alert("Did y ...

Is there a way to embed an AJAX submit form into a notification without the need for page refresh?

I have integrated the jQuery plugin toastr js () for notifications on my website. I am facing an issue where I want to include a contact form within the notification popup and submit it using AJAX. Despite having the form working fine outside of the toastr ...

Why is it that GetElements does not provide immediate results upon execution?

Just diving into the world of Javascript for the first time and experimenting with it on Chrome, but running into unexpected results. When I try: document.getElementsByTagName("h1") I anticipate seeing: <h1>tester h1 in body</h1> Instead, wh ...