What is the best way to calculate the sum of a field within a map?

Having trouble determining how to calculate the total of an array received from an API request. Working with Next.js

{positions.map(position => {
  return (
    <List
      title={position.title}
      slug={position.slug}
      quantity={position.quantity}
      position={position.position}
      price={position.transactionPrice}
      fees={position.fees}
      code={position.assetType.code}
      assetName={position.assetType.name}
      assetType={position.assetType.__typename}
    />
   );
 })}

I aim to sum certain fields (e.g., fees) to display above the list, showing the combined fees for all entries. I've been informed that this cannot be done through the GraphQL API call. How can I achieve this in Next.js/React?

I believe I need to utilize the reduce array method, but unsure where and how to incorporate it into the code. Should it precede the return() statement?

Answer №1

To calculate the overall amount, you can utilize the reduce method:

const totalFees = positions.reduce((accumulator, element) => accumulator + element.fees, 0);

You have the flexibility to incorporate this value into your JSX in any way you prefer:

<div>Total fees: {totalFees}</div>

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

Arrays passed as query parameters to Next.js router.query may result in the value being

When trying to pass objects from an array to another page using router.query, individual objects like router.query.title work as expected. However, when attempting to pass arrays such as router.query.reviews, it returns something like reviews: ['&apos ...

Track user engagement across multiple platforms

Looking for solutions to log system-wide user activity in my Electron app. I want to track mouse-clicks and keystrokes to determine if the user is inactive for a certain period of time, triggering a timer reset within the application. I believe I may nee ...

Horizontal scrolling alone is proving to be ineffective

My current HTML code includes a table that is integrated with PHP Laravel. The data is being pulled from Admin.php to populate the table, resulting in it being wider than the screen window. To address this, I added a horizontal scroll bar for navigation pu ...

When running "npx react-native init client" on Android, the command fails due to the error message stating that tools.jar could not be found. This issue occurs specifically with React

Device: Windows 10 NodeJS Version: v13.8.0 React Native Version: 0.62.2 React Version: "16.11.0" The issue persists even with the typescript template. Upon executing the command npm run android, I encountered the following logs: info Running je ...

What is the optimal parameter order when utilizing pre-curried functions and composition in JavaScript?

We have a simple, mathematically curried function for subtracting numbers: function sub(x) { return function (y) { return x - y; }; }; sub(3)(2); // 1 The function signature matches the obtained result. However, when function composition comes i ...

Is there a way to modify my code to restrict users from liking a post multiple times?

I am currently working on a like system and I have made some progress. However, I am struggling to make it so that the likes only increment once. Does anyone have any insights or suggestions on how to achieve this? I have considered using session variables ...

Deleting a specific row within a Material UI DataGrid in Reactjs: Tips and tricks

As I embark on this React project, things are progressing smoothly. However, a challenge has arisen. The functionality I aim for is as follows: When the checkbox in a row is clicked, I want that particular row to be deleted. For instance, selecting checkb ...

What is the best way to incorporate this into a Vue project?

I am in the process of transitioning my code to Vue.js, so I am relatively new to Vue. In the screenshot provided (linked below), you can see that there are 4 columns inside a div with the class name columns. I attempted to use the index, like v-if='i ...

What is the approach to initiating a jquery function once HTML content is dynamically added through an AJAX call?

<div id="timeline"> <ul class="grow" id="grown"><li>One</li><li>Two</li><li>Three</li><li>Four</li><li>Five</li><li>Six</li><li>Seven</li><li>Eight< ...

Error encountered while rendering content in an Angular template

I'm currently integrating ngx-carousel into my application. Interestingly, the carousel works perfectly when I manually input the data. However, when trying to fetch the data from the server, it fails to work as expected. Take a look at my code snip ...

React: maintaining referential equality across renders by creating closures with useCallback

I want to make sure the event handling function I create in a custom hook in React remains referentially equal across renders. Is it possible to achieve this using useCallback without specifying any variables it closes over in the dependencies list? Will o ...

Ways to navigate by percentage in react

I'm working on a flexbox that scrolls horizontally with boxes set to 25% width. Currently, I have it scrolling by 420px which is causing responsive issues. Is there a way to implement the scroll using percentages instead of fixed pixel values in React ...

Loading intersecting objects with FBXLoader in Three.js

After successfully loading an fbx file using FBXLoader and adding it to the scene object, I encountered an issue where I couldn't interact with the object on click to apply transform controls. Interestingly, all other objects were clickable except for ...

"Auth.currentSession is indicating that there is no user currently logged in

I am currently working on a basic React app with authentication using aws-amplify. My user pool is set up in Cognito and I can successfully redirect the user to the hosted UI for login. However, when trying to retrieve the current session, I am receiving a ...

What is the process for moving entered data from one text box to another text box when a checkbox is selected?

I need help with a function that reflects data entered in one text box to another text box when a checkbox is ticked. The checkbox is initially checked and the values should change when it is unchecked and then checked again. Currently, the code is only ou ...

A guide to successfully sending the 'onClick' function to a child component within React

In my coding project, I have developed a versatile Modal component that can be customized with different headers, bodies, and footers, as well as various arguments for the Reactstrap components. While I am using Reactstrap to create the Modal, the issue is ...

Why is the image cut in half on mobile devices but displaying correctly on computer screens? Could it be an issue with

There seems to be an issue on mobile screens that does not occur on computer screens. When the user clicks on the image, it disappears, and when they click another button, it reappears. However, there is a problem with how the image appears - it is cut off ...

The function 'appendChild' is not recognized on the type 'unknown'.ts(2339)

I'm encountering an issue while trying to integrate the Utterances component into my articles. Upon attempting to build the site, I receive the following error message: "Property 'appendChild' does not exist on type 'unknown' ...

Ways to pause the clock, once the designated time has run out in 'jQuery Countdown'

When the specified time has elapsed, I trigger an 'Ajax Request'. The issue arises when the time is up, causing the 'Ajax Request' to continue running every second. Here is my 'AJAX CODE': var startdate = '2017-05-15 ...

Filtering data in AngularJS by parsing JSON records

I have a JSON file containing restaurant information and I need to display the data by grouping them based on their respective address fields. For example, all restaurants with the address 'Delhi' should be shown first, followed by those from &ap ...