Chart JS Advanced Mode + Xano

Hello everyone,

I’m using chart js advanced mode and I’m trying to figure out how am I going to replace the information from Labels and Datasets with the information from fetched collections.

See these examples below:

I have a chart like this
image

This is my label
return ['January', 'February', 'March', 'April', 'May', 'June', 'July'];

This is my dataset

return [{
    label: 'Receita',
    data: [12000, 15000, 8000, 18000, 20000, 24000, 22000],
    fill: true,
    borderColor: '#887EF2',
    backgroundColor: function(context) {
        const chart = context.chart;
        const {ctx, chartArea} = chart;
        if (!chartArea) {
            return null;
        }
        const gradient = ctx.createLinearGradient(0, chartArea.top, 0, chartArea.bottom);
        gradient.addColorStop(0, 'rgba(136, 126, 242, 0.50)');
        gradient.addColorStop(1, 'rgba(255, 255, 255, 0)');
        return gradient;
    },
    tension: 0.5,
    borderWidth: 2,
    pointRadius: 0
}];

I wonder how I replace
return ['January', 'February', 'March', 'April', 'May', 'June', 'July'];
and
data: [12000, 15000, 8000, 18000, 20000, 24000, 22000],
with the information fetched from Xano’s database.

Can someone help me on this?

Ps. I don’t know any javascript. All of these were made with chatgpt.

Thanks!

Hi @albarracim Filippe,

I can tell you how I did it in my case. Just as a disclaimer, I do not have a technical background and I pretty much learn by doing on Weweb so I can’t guarantee what I say is 100% correct. It just worked out for my project :partying_face: :champagne:

Step 1:
Let’s first talk about data structure. In this case, the amount of ice cream sold by a vendor per year, is stored in the collection “ice cream”.
image
The dataset and the labels must be “aligned” (if you have not, watch @Joyce 's video https://www.youtube.com/watch?v=ABblukrYKp0 ). If there are mixed (i.e. the amount of ice cream sold in 2021 is not 16000), it won’t work.
So I recommend having such a table on Xano, that is sorted the way you present the data, in this case by ascending years ( I did not manage to apply the sort filter on Weweb…and don’t know why). If you don’t know how to do it please let me know I can show you.

Step 2:
Bind collections to dataset and labels.

Let’s start with the dataset: first you need to get the right column within your collection (in my case “ice cream” is “chart_y_tot_std.data”) using the formula in no-code. To do so I did this:
image
The roll-up formula returns all values from a key, here the “period” column (the “amount” in the first screenshot).
What I do next is to “convert” it to javascript. To do so,simply click on the above dropdown and select javascript .
image
Then you can insert this part replacing your array like this: data: [12000, 15000, 8000, 18000, 20000, 24000, 22000] =>
image

Connect on the chartJS website to finish your chart by inserting this part within the javascript code => Line Chart | Chart.js

Apply the same logic for labels and you are good to go.

I hope it helped! Let me know in case I can help further.

Hello!

So simple as that. Thanks a lot! Worked perfectly.

Actually what I did was to use javascript for a Lambda Function at XANO and the API returned the array. No need to rollup.

I’m not a technical guy as well so I can give you a hint. If you want to do the same, try using ChatGPT for Lambdas at XANO. It works great!

Happy to help !
How cool for the Lambda! Can you show ?

PS: if you got your answer don’t forget to “tick the solution” on the answer so that people know it’s solved

Solution ticked! =) Sorry, I missed that.

Regarding Lambdas, take a look:

I decided to use two functions, but you can use only one that brings up how many results you want.

The logic is in portuguse, but you can ask your gpt to translate it :stuck_out_tongue_winking_eye:
By providing these examples to your GPT, you would be able to do anything I guess… Try using Javascript at weweb too. It simplifies lots of things.

// Obter as transações de afiliados
let transactions = $var.affTransaction;

// Inicializar variáveis
let labels = [];
let currentDate = new Date();
const mesesPortugues = ['Janeiro', 'Fevereiro', 'Março', 'Abril', 'Maio', 'Junho', 'Julho', 'Agosto', 'Setembro', 'Outubro', 'Novembro', 'Dezembro'];
const diasDaSemanaPortugues = ['Domingo', 'Segunda', 'Terça', 'Quarta', 'Quinta', 'Sexta', 'Sábado'];

// Função auxiliar para verificar granularidade
function verificaGranularidade(transactions, granularidade) {
    let datas = transactions.map(t => new Date(t.created_at).toISOString().slice(0, granularidade));
    let datasUnicas = [...new Set(datas)];
    return datasUnicas.length;
}

// Lógica de consolidação
if (verificaGranularidade(transactions, 7) >= 12) { // Mês
    for (let i = 0; i < 12; i++) {
        let month = new Date(currentDate.getFullYear(), currentDate.getMonth() - i, 1);
        labels.unshift(mesesPortugues[month.getMonth()]);
    }
} else if (verificaGranularidade(transactions, 10) >= 4) { // Semana
    for (let i = 0; i < 4; i++) {
        labels.unshift(`Semana ${4 - i}`);
    }
} else { // Dia
    for (let i = 0; i < 7; i++) {
        let day = new Date(currentDate);
        day.setDate(currentDate.getDate() - i);
        labels.unshift(diasDaSemanaPortugues[day.getDay()]);
    }
}

// Retornar os labels
return labels;
// Obter as transações de afiliados
let transactions = $var.affTransaction;

// Inicializar variáveis
let data = [];
let currentDate = new Date();

// Função auxiliar para verificar granularidade
function verificaGranularidade(transactions, granularidade) {
    let datas = transactions.map(t => new Date(t.created_at).toISOString().slice(0, granularidade));
    let datasUnicas = [...new Set(datas)];
    return datasUnicas.length;
}

// Lógica de consolidação
if (verificaGranularidade(transactions, 7) >= 12) { // Mês
    for (let i = 0; i < 12; i++) {
        let month = new Date(currentDate.getFullYear(), currentDate.getMonth() - i, 1);
        let total = transactions
            .filter(t => new Date(t.created_at).getMonth() === month.getMonth())
            .reduce((sum, t) => sum + t.subtotal, 0);
        data.unshift(parseFloat(total.toFixed(2)));
    }
} else if (verificaGranularidade(transactions, 10) >= 4) { // Semana
    for (let i = 0; i < 4; i++) {
        let weekStart = new Date(currentDate);
        weekStart.setDate(currentDate.getDate() - (i * 7));
        let total = transactions
            .filter(t => new Date(t.created_at) >= weekStart && new Date(t.created_at) < new Date(weekStart).setDate(weekStart.getDate() + 7))
            .reduce((sum, t) => sum + t.subtotal, 0);
        data.unshift(parseFloat(total.toFixed(2)));
    }
} else { // Dia
    for (let i = 0; i < 7; i++) {
        let day = new Date(currentDate);
        day.setDate(currentDate.getDate() - i);
        let total = transactions
            .filter(t => new Date(t.created_at).toDateString() === day.toDateString())
            .reduce((sum, t) => sum + t.subtotal, 0);
        data.unshift(parseFloat(total.toFixed(2)));
    }
}

// Retornar os datasets
return data;