#Math on array.map function with rendered items props

1 messages · Page 1 of 1 (latest)

oblique whaleBOT
#

Hi @strange sable. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:

#

Based on the provided extracts, it seems you're trying to sum a property from each item in an array using the map function in a server-side rendered Next.js application. However, it's important to note that the map function is not the best choice for this operation. The map function is used to create a new array with the results of calling a provided function on every element in the array. It's not designed to return a single output value from an array, which is what you're trying to do.

Instead, you should use the reduce function, which is specifically designed to apply a function against an accumulator and each element in the array (from left to right) to reduce it to a single output value.

Here's how you can use reduce to sum the online property from each players object in your data array:

const totalPlayers = data.reduce((total, server) => total + (server.data.players?.online || 0), 0);

This code will add the online property from each players object in your data array to a total accumulator, which starts at 0. If server.data.players?.online is undefined, it will add 0 instead to avoid NaN errors.

Please note that this code should be placed outside of the Servers component to avoid unnecessary computations on each render.

Also, remember that in Next.js, data fetching for server-side rendering should be done in a getServerSideProps function, which is not present in your code. You can learn more about this in the Next.js Documentation (https://nextjs.org/docs/pages/building-your-application/data-fetching/get-server-side-props).

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: