DEV Community

Discussion on: Help? .map .reduce

Collapse
 
ecyrbe profile image
ecyrbe • Edited

just do setChartdata1(chartData)

import React, { useState, useEffect } from "react";
import Chart from "react-google-charts";
import api from '~/services/api';
import { Container } from './styles';
import { startOfDay, endOfDay } from 'date-fns';

// put your independant functions outside your components
const sum = (a, b) => a+b;
const uniqueCategories = (array) => [...new Set(array.map(item => item.category))];


function Products() {
  const [chartdata1, setChartdata1] = useState([["Category","value"],["Categoria1", 16.6]])
  useEffect(() => {
    async function loadchart() {
      const date1 = startOfDay(new Date())
      const date2 = endOfDay(new Date())
      const response = await api.get('sales', {
        params: { date1, date2 }
      });
      const apiResult = [
        {name: "test1", category: "Categoria1", price: 3},
        {name: "test2", category: "Categoria1", price: 13.6},
        {name: "test3", category: "Categoria2", price: 8},
        {name: "test4", category: "Categoria2", price: 8}
      ];
      const chartData = uniqueCategories(apiResult).map(category => [
        category,
        apiResult
          .filter(item => item.category===category)
          .map(item => item.price)
          .reduce(sum)
      ]);
      setChartdata1([["Category","value"],...chartData]);
   }
   loadchart();
  },[]);
Thread Thread
 
cristiantsantos profile image
cristiantsantos

I had done it, really, and it hadn't worked.

Now it worked.

Thank you very much, I don't know how to thank you. I've been in this for 2 days.

Thank you