Calculating total amount for a certain field in Supabase

Here is how I wrote my supabase query with nuxt3:

const client = useSupabaseClient()
const { data: expenses } = await useAsyncData('count', async () => {
  const { data, count } = await client.from<Expenses>('expenses').select('amount, currency', { count: 'exact' })
  return { data, count }
})
console.log('useAsyncData :', expenses.value)

This is the outcome of my query:

https://i.sstatic.net/l8eDX.png

I am looking to calculate the sum of amounts and group them by currency

The desired result in mind:

const result = { 0: 33800, 1: 10 }

Answer №1

If you want to customize the result of your operation using the transform property in the useAsyncData function, you can do so by following this example:

    const { data: expenses } = await useAsyncData("count", async () => {
        const { data } = await ...
        return data;
    }, {
        transform: (data) => {
            const result = {};

            const groups = data.reduce((acc, d) => {
                const found = acc.find((a) => a.currency === d.currency);
                const value = { amount: d.amount };
                if (!found) {
                    acc.push({ currency: d.currency, data: [value] });
                } else {
                    found.data.push(value);
                }
                return acc;
            }, []);

            groups.forEach((group) => {
                result[group.currency] = group.data.map(i => i.amount).reduce((a, b) => a + b);
            });

            return result;
        }
    });

The transformed output will look like this:

{
  "0": 33800,
  "1": 10
}

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 could be causing the button ID to not update in jQuery after being clicked multiple times?

Hello there! I'm currently tackling the challenge of dynamically altering the ID of a button when other buttons are clicked. Here's the situation: I have one search button with the ID #searchButton, and three additional buttons with IDs #changeB ...

Retrieve documents in MongoDB that rely on information from other documents

Consider the following mongoose model: const UserSchema = Schema({ //_id: ObjectId, //more fields, blockedIds: [{ type: ObjectId, ref: 'User' }] }) What would be the most optimal approach to retrieve all users who do not have th ...

Simple steps to load various json files into separate json objects using node.js

I am new to working with Json and node.js My goal is to load a json file into a JsonObject using node.js, but I have been struggling to accomplish this task. I have created two files, one named server.js and the other jsonresponse.json. My objective is t ...

Tips for utilizing a vue.js nested for loop with two arrays using v-for

The issue has been resolved, and both my parent view and child component code are now correct and functioning properly I am using Vue.js with the goal of iterating similarly to a nested for loop to display a matrix table. Initially, I tried to achieve thi ...

Encountering an error of "Cannot access property 'PluginKey' of undefined" while utilizing @toast-ui/editor in a JavaScript project

Struggling with integrating the @toast-ui/editor into my native JavaScript project. The editor is not displaying due to this error message: Cannot read property 'PluginKey' of undefined" This error is specifically within the toastui-editor ...

Using the onclick attribute as a unique identifier for a button

I am currently facing a challenge with a form that does not have an ID Here is the code snippet in question: <button class="btn btn-primary" onclick="showModal()" type="button">Browse Data</button> Unfortunately, I don't have any contro ...

The error message states that the property '$refs' cannot be found on the void type

Attempting to automatically focus on the next input field after typing 1 character. Encountering error: The property '$refs' does not exist on type 'void'. Here is the code snippet: setup() { const autoFocusNextInput = (event, max: ...

Loading `.obj` and `.mtl` files in THREE.js with accompanying PNG textures

I am facing an issue while attempting to load an mtl file with reference to png textures for my obj model. The error I am encountering is as follows: TypeError: manager.getHandler is not a function Below is the snippet of my three.js code: var loadOBJ = ...

Increase the visibility of a div using Jquery and decrease its visibility with the "

Can anyone assist me with implementing a "show more" and "show less" feature for a specific div? I have put together a DEMO on codepen.io In the DEMO, there are 8 red-framed div elements. I am looking to display a "show more" link if the total number of ...

Utilize Lodash to iterate through functions in a loop and retrieve the first matching result

I am looking to iterate through an array of objects and call a method on them. If the result of that method meets certain conditions, I want to immediately return that result. The current implementation is as follows: public getFirstMatch(value: string, a ...

Oops! There was an error: Unable to find a solution for all the parameters needed by CountdownComponent: (?)

I'm currently working on creating a simple countdown component for my app but I keep encountering an error when I try to run it using ng serve. I would really appreciate some assistance as I am stuck. app.module.ts import { BrowserModule } from &apo ...

Prevent Vue.js from bundling the settings file into the build

I have set up the vue-webpack template and created a settings.json file to hold environment variables that need to be changed during script installation. Content of my settings.json file (containing the API server's absolute path): { "apiURL": "// ...

JavaScript and jQuery radio button matrix group implementation

I'm feeling completely lost when it comes to solving this problem. My task is to create a matrix of radio buttons with columns labeled 1 to 3 and rows labeled A to C. A B C 1 (o) (o) (o) 2 (o) (o) (o) 3 (o) (o) (o) <tabl ...

JavaScript modal component malfunctioning

I'm having an issue with the bootstrap 4 modal component. Whenever I click the button, the modal window fails to appear. Can someone offer assistance? <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModal"> ...

Finding a way to exit a Nested StackNavigator

Is there a way to smoothly navigate from a deeply nested StackNavigator and DrawerNavigator setup while preventing the user from returning to the previous screen? Here is the layout of the views: const login = StackNavigator( { loginScreen: { scr ...

Configuring unique capabilities for the Selenium WebDriver

My goal is to customize the settings of a Selenium Webdriver. In this particular case, I am looking to modify a capability of the webdriver specifically for the Firefox browser. All of this needs to be done using Javascript. this.driver = new selenium.Bu ...

Angular's Child Component At Its Best

As I develop an application with a consistent design pattern for lists of elements, I find myself creating specific components for different object types. For instance, when dealing with objects of type A, I create AComponent which takes in input a, follow ...

Chrome tab freezes when scrolling with the mouse

Working on a particularly interesting bug, I've managed to replicate it using a fiddle. The issue arises when the middle mouse button is clicked over the div element containing text, causing the pointer to become stuck. Is this possibly a browser bug ...

Inject components in Angular using dependency injection

Can components in Angular be dependency injected? I am interested in a solution similar to injecting services, like the example below: my.module.ts: providers: [ { provide: MyService, useClass: CustomService } ] I attempted using *ngIf= ...

Kendo UI Scheduler: The system encountered an overflow while converting to a date and time format

Working on a project using .NET MVC and the Kendo UI Scheduler, an open-source tool. The goal is to save, read, update, and delete events from the scheduler into the database using JavaScript. Encountering some challenges in the process - when attempting ...