Tips for merging two arrays in NextJS?

I need help with a minor issue I'm facing.

In my app, I am creating data tables and retrieving data from two different API endpoints. The first endpoint returns data like this (e.g. offers):

{
 id: 1,
 product_id: 1,
 name: 'some name',
 etc...
}...

And the second one (e.g. products) returns data like this:

{
 id: 1,
 name: 'some name',
 etc...
}...

What I want to achieve is to retrieve the first array but replace the product_id with the actual product name.

Here is what I have done so far:

const [offers, setOffers] = React.useState(null);
const [products, setProducts] = React.useState(null);

React.useEffect(() => {
 fetch(`http://localhost:3000/api/offers`)
 .then((res) => res.json())
 .then((data) => {
  setOffers(data.data);
 });

 fetch(`http://localhost:3000/api/products`)
 .then((res) => res.json())
 .then((data) => {
   setProducts(data.data);
 });
}, []);

However, I am now stuck at this point and unsure about how to proceed.

Answer №1

Make sure your React code is structured like this:

const [users, setUsers] = React.useState(null);
const [posts, setPosts] = React.useState(null);

React.useEffect(() => {
 const promises = Promise.all([
   fetch(`http://localhost:3000/api/users`).then((res) => res.json()),
   fetch(`http://localhost:3000/api/posts`).then((res) => res.json())
 ]);
 promises.then((
   [usersResp, postsResp]
 ) => {
   const users = usersResp.data;
   const posts = postsResp.data;
   setPosts(posts);
   return users.map((user) => {
     const post = posts.find(p => p.id === user.post_id);
     if(post) {
       return {
         ...user,
         post_id: post.title
       }
     }
     return user;
   })
 }).then(users => {
   setUsers(users);
 })
 .catch(err => {
   // handle any errors here
 });
}, []);

Answer №2

Ensure you retrieve your products before calling the setOffers function

setOffers(offers.map((offer) => (
   {
    ...offer,
    product_name: products.find((product) => product.id == offer.product_id)?.name
   }
 )
))

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

When utilizing <Typography> in React, the text remains unbroken

The text "Welcome Back! We are happy that you are with us!" is not breaking after the phrase "Welcome Back". Both phrases appear on the same line and do not break apart. I attempted to fix this issue by modifying the code, but the problem persists. The ou ...

How to customize Material UI Autocomplete options background color

Is there a way to change the background color of the dropdown options in my Material UI Autocomplete component? I've checked out some resources, but they only explain how to use the renderOption prop to modify the option text itself, resulting in a a ...

Error: Unable to access the 'version' property of null

Having trouble installing any software on my computer, I've attempted various solutions suggested here but none have been successful. $ npm install axios npm ERR! Cannot read property '**version**' of null npm ERR! A complete log of this ru ...

Resetting forms in React upon submission

After successfully submitting a form using Axios, I'm facing an issue where the data in each text field remains on the page instead of getting cleared. I attempted to incorporate a resetForm function to reset the form back to its original blank state, ...

Issues with React router arise once the app has been built

I am new to utilizing react and react-router in my project. I have built the application using create-react-app and now I am facing an issue with routing between two main pages. After trying different approaches, I managed to get it working during develop ...

What are some strategies to enhance the efficiency of this code and reduce repetition?

Here's an overview of the component in question export default () => { const { currentUser, logout } = useAuth(); const [sideBarOpen, setSideBarOpen] = useState(false); const theme = useTheme(); const classes = useStyles(); const isSmall ...

React Native state remains unchanged

I've been struggling for hours trying to pass a string from AsyncStorage to a state variable using hooks, but I can't seem to get it to work. Here is the code snippet: const [cartitems, cartitemsfunc] = useState(''); const d = async () ...

React: Issue with passing arguments to redux action hooks

In my React application, I have implemented Redux-Toolkit to manage reducers and actions with slices. I am currently working on creating actions that can update and delete values from the store, requiring arguments for their usage. To achieve this, I have ...

When the state changes in React, the useSelector hook does not provide real-time updates

Currently, I am in the process of implementing a search feature using React and Redux Thunk. The main requirement for this search functionality is to fetch data from an API by calling a thunk action and updating the state accordingly for display on the UI. ...

When switching from page 1 to page 2 in a React MUI Data table, the cell data does not update to reflect the API response

Imagine a scenario where there is a parent component containing a child component that acts as a MUI data table. This child component receives API response data from the parent component as props. Problem: The data in the table loads perfectly on initial ...

Using the Firebase Admin SDK for user creation on the server side

**While working on my CRUD project, I encountered an issue where the admin needed to add a user in the documentation as well as in the authentication process. Using the normal SDK would simply replace the current user, so I attempted to use the admin SDK. ...

Utilize JSON categories to assign groups to TextFields or Selects according to a JSON data attribute

I have retrieved multiple JSON groups from an API, each containing one or more questions objects. My goal is to display each question along with its corresponding response in a MUI TextField or Select component, based on the value of QuestionType. Current ...

Guide on integrating a php script into a react application

I'm currently in the process of setting up a functional contact form on my website by following the guidance provided in this article link. However, the tutorial includes a php script to manage the post data, and I am using create-react-app and unsure ...

What benefits does React offer that jQuery does not already provide?

What sets ReactJS apart from jQuery? If jQuery can already handle everything, why should we use React? I've tried to research on Google but still don't have a clear answer. Most explanations focus on terms like "views," "components," and "state" ...

What is the best way to align these divs horizontally?

I am facing an issue with my web page layout. I have a list of topics that I need to display, with four topics in each row. However, when I try to render them, they end up aligning vertically instead of horizontally like this: This is the CSS code snippet ...

Is the state of the React.js component empty?

HTML: <!-- index.html --> <!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>React Tutorial</title> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.6/react.js"></script> ...

Retrieving the initial value of Material UI Date Picker in conjunction with React Hook Forms

I'm currently in the process of creating a form with Material UI that includes three fields: Date, Hours, and Comments. The issue I'm encountering is that the MUI Date picker field defaults to today's date, which means that when I fill out t ...

A step-by-step guide on how to use code to verify a Material-UI check-box

Currently, I have integrated Material-UI's Checkbox component into my application along with a corresponding label. I am looking to make both the checkbox and the label clickable. However, I am unable to utilize their FormControlLabel component (feat ...

What is the process for setting up 127.0.0.1 with port 127.0.0.1:8000 in the .httaccess file?

Is there a way to set up a sub domain in Node.js while running on port 127.0.0.1:8000? Here is the .httaccess code: RewriteEngine On RewriteRule ^$ http://127.0.0.1:8080/ [P,L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d Rewrit ...

Tips for ensuring that a nested object in an array contains only a single object

My array is structured like this: [ { object1:{ childObj1:[grandChild1,grandChild2], childObj1, childObj1} }, { object2:{ childObj1:[grandChild1,grandChild2], childObj1, childObj1} }, { object3:{ childObj1:[grandChild1,grandChild2 ...