I’m doing a React project. I have two reutilizable functions that made requests to an API. When I call the functions, react raise the error:
Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
1. You might have mismatching versions of React and the renderer (such as React DOM)
2. You might be breaking the Rules of Hooks
3. You might have more than one copy of React in the same app
I have fetchCustomers.jsx:
export default function fetchCustomers() {
const [customers, setCustomers] = useState([]);
useEffect(() => {
const fetchData = async () => {
try {
const response = await axios.get('customers/', {
headers: {
'Authorization': `Bearer ${localStorage.getItem('access_token')}`
}
});
setCustomers(response.data);
} catch (error) {
console.error("Error al obtener los datos de clientes.", error);
}
};
fetchData();
}, []);
return customers;
}
fetchSales.jsx:
export default function fetchSales(params = {}) {
const [sales, setSales] = useState([]);
useEffect(() => {
const fetchData = async () => {
try {
const response = await axios.get('sales/', {
params: params,
headers: {
'Authorization': `Bearer ${localStorage.getItem('access_token')}`
}
});
setSales(response.data.results);
} catch (error) {
console.error("Error al obtener los datos de ventas.", error);
}
};
fetchData();
}, []);
return sales;
}
and cobrar.jsx:
export default function Cobrar() {
const [filter, setFilter] = useState({
startDate: null,
endDate: null,
customer: null,
uncharged: true,
});
const [customers, setCustomers] = useState([]);
const [sales, setSales] = useState([]);
useEffect(() => {
const fetchData = async () => {
try {
const customersResponse = fetchCustomers();
setCustomers(customersResponse);
const salesResponse = fetchSales();
setSales(salesResponse);
} catch (error) {
console.error("Error al obtener los datos.", error);
}
}
fetchData();
}, []);
I tried call the functions in the const and works but I can’t filter the sales by params. I want to get all the sales and then filter by daterange and some fields.