0

I am trying to show some data into a nivo line chart. If i only send expenses via an API everything works fine, but when i want to add incomes to the mockData state which i'll pass it to the nivo line chart, it won't gonna show in the line chart + the useEffect will be triggered twice for the incomes.

I tried adding some hardcoded data after i set mockData with expenses and it will work fine and in my line char i'll have 2 separate lines one for expenses the other one for the hardcored that. And like i said the problem is when i want to add the incomes to the mockData state and to get the information on my line chart.

  const [expenses, setExpenses] = useState([]);
  const [incomes,setIncomes] = useState([]);
  const [mockData, setMockData] = useState([]);
  const email = "messi";
  const res = [];

  useEffect(() => {
    const fetchExpenses = async () => {
      const request = await fetch(URL1);
      const response = await request.json();
      return response;
    };
    const fetchIncomes = async () =>{
      const request2 = await fetch(`http://localhost:8080/api/income/get-incomes-current-month/messi`);
      const respones2 = await request2.json();
      return respones2;
    }

    fetchExpenses().then((data) => {
      setExpenses(data);
      setMockData([{
        id: "expenses",
        color: "hsl(0, 35%, 78%)",
        key:1,
        data: data.map((exp) => ({ x: exp.expenseCategory, y: exp.amount })),
      }]);
    });
 
    fetchIncomes().then((data)=>{
      setIncomes(data);
      setMockData(mockData=>[...mockData,
        {
        id:"incomes",
        color: "hsl(0, 55%, 55%)",
        key:2,
        data: data.sort((a,b) => new Date(a.date) - new Date(b.date)).map((i) => ({ x: i.incomeCategory, y: i.amount })),
      }])
    });

  }, []);


  console.log(mockData)

  return mockData;
}

any ideas?

0 Answers0