Utilizing the `promise.all` object in a useState hook

Can anyone help me with setting up an object to use useState? I am working with the dataMap object that needs to be passed to the setResults function. Any assistance would be greatly appreciated! ?

export default function Home() {
  const [results, setResults] = useState([]);

  const fetchResults = async () => {
    const res = await fetch(
      'someurl'
    );
    const data = await res.json();
    const dataMap = data.reduce((acc, curr) => {
      return {
        ...acc,
        [curr.id]: curr
      };
    }, {});

    const requests = Object.keys(dataMap).map(async (productId) => {
      const request = await fetch(
        `someUrl/${productId}`
      );
      const response = await request.json();
      return response;
    });
    const responseAll = await Promise.all(requests);
    responseAll.forEach(
      ({ id, color }) => (dataMap[id] = { ...dataMap[id], color })
    );  
    //console.log(dataMap);
    setResults(dataMap)
  };

Answer №1

const apiRequests = Object.keys(dataMap).map(async (productId) => {
      const request = await fetch(
        `someUrl/${productId}`
      );
      const response = await request.json();
      return response;
    });

This code snippet executes all the API calls corresponding to each entry in Object.keys(dataMap)

To update the state with the returned values.

You should update the state immediately after the await statement like this:

 const apiRequests = Object.keys(dataMap).map(async (productId) => {
      const request = await fetch(
        `someUrl/${productId}`
      );
      const response = await request.json();
      setResults(prev => [...prev, response])
    });

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

The styling for Material-UI 5 DataGrid does not remain exclusive to individual components

Recently, I made the switch from Material-UI v4 to v5 (now MUI) and encountered a problem with the DataGrid component conflicting with other components like Select. The issue arises from additional styles loaded by the DataGrid causing interference. An ex ...

The NextUI Table example encounters an issue with a TypeError, specifically stating that it is unable to read properties of undefined, specifically referring to the

Seeking assistance with a React error as I am relatively new to the framework. While I have some basic knowledge of client and server side rendering, this particular issue has stumped me. Following this example: Use Case Example When creating a table, yo ...

Adjust the initial scroll position to - apply overflow-x: scroll - on the specified element

I have an image that can be scrolled to the right on screens that do not fit the full width, but I want the center of the image to be displayed first instead of the left side. Below is my React code: import React, { useEffect, useRef, useState } from &qu ...

Retrieving external parameters within an internal map within a dynamically created array of elements

I'm attempting to retrieve an array of elements within a JSX template from a nested object in this manner: <Menu id="menu-locations" anchorEl={this.state.anchorElLocationsMenu} anchorOrigin={{ vertical: 'top', ...

What causes the typescript error in my code: The argument being passed is either a string, an array of FilterData, an array of numbers, or an array of Moments, which is not compatible with a parameter of type 'string'?

When writing my code, I have the need to utilize various types for different scenarios. Depending on the situation, the type may be a string, number[], FilterData[] (a custom type), or Moment[]. To address this requirement, I defined the type as: export ty ...

Using React Typescript to Assign Custom Types to Material UI TextField MenuItem Values

I encountered a type conflict in my code, unsure whether a simple casting solution exists or if there is a more fundamental issue at play. import React from "react"; import TextField from "@mui/material/TextField"; import MenuItem from ...

Guidelines for implementing a seamless transition effect on elements with Tailwind CSS

I successfully created a responsive nav bar using Tailwind CSS in Next.js, and it is functioning perfectly. https://i.stack.imgur.com/yTCbs.png https://i.stack.imgur.com/rdXhL.png https://i.stack.imgur.com/J8fM6.png Everything works well, except when I ...

What is the process for redirecting an API response to Next.js 13?

Previously, I successfully piped the response of another API call to a Next.js API response like this: export default async function (req, res) { // prevent same site/ obfuscate original API // some logic here fetch(req.body.url).then(r => ...

Managing Autocomplete Functionality in React with Material-UI, Both with and without a Pre

I am in need of an Autocomplete feature that offers the following functionalities: If the initial value has an id greater than 0, then I want the autocomplete to default to the provided object. If the initial value has an id less than or equal to 0, then ...

The useEffect function continues to run every time, regardless of whether there have been changes in its

We utilize a UserContext in our application to store user information for easy access. However, the UserContext keeps making unnecessary API calls even when the dependency hasn't changed. import React, { useState, useEffect } from 'react&apos ...

The map functionality within the TextField component is invalid when being used within the material-ui component

The issue arises with the map function in TextField when it is located within a component from material-ui library. I have two TextFields, where the radio button functionality works in the first one but not in the second. How can I ensure that the radio b ...

Ways to separate handleSubmit() functions in React Hooks Form to prevent them from intermingling when nested within each other

I recently integrated React Hook Form into my Next JS App for handling forms. In my setup, I have two form components named FormA and FormB. However, I encountered an issue where triggering the handleSubmit() function for FormB also triggered the handleSub ...

What are the differences between using the open prop and conditionally rendering a Material-UI Modal component?

Is there a difference in using the open prop or conditionally rendering Material-UI's Modal component and its built components? The closing transition may be lost, but are there any performance advantages when dealing with multiple Modals? Example wi ...

Issue: receiving an error message "Error: spawn wslvar ENOENT" while attempting to run yarn storybook on

Currently, I am attempting to follow a tutorial found at The tutorial provides the following set of commands: # Clone the template npx degit chromaui/intro-storybook-react-template taskbox cd taskbox # Install dependencies yarn # Run the test runner (J ...

Securing my Next.js APIs for controlled access in my application

I'm currently developing a Next.js application and I want to secure access to my APIs so that only my application can make requests to them. In a previous project using the MERN stack, I utilized cors to restrict API access to my domain. However, it ...

What is the best way to have a button activate a file input when onChange in a React application?

Having an input field of file type that doesn't allow changing the value attribute and looks unattractive, I replaced it with a button. Now, I need the button to trigger the input file upon clicking. How can this be achieved in React? Edit: The butto ...

How can I fix the error saying "prop-types not detected on request"?

I'm embarking on a fresh ReactJS project utilizing material-ui Next along with fuse-box. All necessary dependencies have been successfully installed: "dependencies": { "material-ui": "^1.0.0-beta.27", "material-ui-icons": "^1.0.0-beta.17", ...

Guide for launching Electron on a local host server during development and for production builds

I have a project using Next.js + Electron + Typescript. I used the npx create-next-app --example with-electron-typescript command to generate the initial code. When I run npm run dev (which actually runs npm run build-electron && electron . ), the ...

What could be causing my Alert component to keep triggering repeatedly?

This is my custom React Native script. import React, { useState, useEffect } from 'react'; import { Alert, View, Image, StyleSheet, Animated, Easing, TouchableOpacity, Text, ScrollView, ImageBackground, Dimensions, TextInput } from 'react-na ...

"When attempting to render a Node inside the render() method in React, the error message 'Objects are not valid as a React child' is

On my webpage, I have managed to display the following: export class OverworldComponent extends React.Component<OverworldComponentProps, {}> { render() { return <b>Hello, world!</b> } } However, instead of showing Hello, ...