Eu tenho o seguinte hook que executa as chamadas a API sem problema, retornando as informações e atualizando os componentes normalmente, mas ele traz alguns erros de conexão no console, creio que esses erros acontecem quando executo a aplicação antes de retornarem as respostas da API, mas como estou usando async await não entendo porque os erros estão ocorrendo, alguém consegue me ajudar com isso:
import { useEffect, useContext } from "react";
import FinancesDataService from "../services/FinancesService";
import { AppContext } from "../components/context/AppContext";
export const useDetails = () => {
const { state, dispatch } = useContext(AppContext);
const { selectedPeriod, profit, cost } = state;
useEffect(() => {
async function countTransactions() {
const response = await FinancesDataService.countTransactions(
selectedPeriod
);
dispatch({ type: "setCounter", payload: response.data });
}
countTransactions();
async function getProfit() {
const response = await FinancesDataService.getProfit(selectedPeriod);
dispatch({ type: "setProfit", payload: response.data });
}
getProfit();
async function getCost() {
const response = await FinancesDataService.getCost(selectedPeriod);
dispatch({ type: "setCost", payload: response.data });
}
getCost();
function calcBalance(profit, cost) {
return profit - cost;
}
dispatch({ type: "setBalance", payload: calcBalance(profit, cost) });
}, [dispatch, selectedPeriod, cost, profit]);
return {
counter: state.counter,
profit: state.profit,
cost: state.cost,
balance: state.balance,
};
};
CONTROLLER:
const FinancesModel = require("../model/FinancesModel");
const findPeriods = async (_, res) => {
try {
const periods = await FinancesModel.distinct("yearMonth");
res.send(periods);
} catch (error) {
res.send(error);
}
};
const countTransactions = async (req, res) => {
const period = req.params.period;
try {
const counter = await FinancesModel.countDocuments({ yearMonth: period });
console.info(counter);
res.send(counter.toString());
} catch (error) {
res.send(error);
}
};
const getProfit = async (req, res) => {
const period = req.params.period;
try {
const profit = await FinancesModel.aggregate([
{ $match: { $and: [{ yearMonth: period, type: "+" }] } },
{ $group: { _id: null, value: { $sum: "$value" } } },
]);
res.send(profit[0].value.toString());
} catch (error) {
res.send(error);
}
};
const getCost = async (req, res) => {
const period = req.params.period;
try {
const cost = await FinancesModel.aggregate([
{ $match: { $and: [{ yearMonth: period, type: "-" }] } },
{ $group: { _id: null, value: { $sum: "$value" } } },
]);
res.send(cost[0].value.toString());
} catch (error) {
res.send(error);
}
};
module.exports = { findPeriods, countTransactions, getProfit, getCost };