Список продаж
Код: Выделить всё
import React, { use, useState, useEffect } from 'react';
import { Table } from 'antd';
import UpdateList from '../hooks/updateList';
const SalesList = () => {
const { list, loading, error, updateList } = UpdateList();
useEffect(() => {
updateList();
}, []); /* If I add updateList within the [], it works, but it enters an infinite loop */
useEffect(() => {
console.log('List updated in the component:', list);
}, [list]);
const columns = [
{
title: 'Name',
dataIndex: 'name',
key: 'name',
},
{
title: 'Price',
dataIndex: 'price',
key: 'price',
},
{
title: 'Quantity',
dataIndex: 'quantity',
key: 'quantity',
},
{
title: 'Amount Received',
dataIndex: 'amountReceived',
key: 'amountReceived',
},
];
if (loading) return Loading...;
if (error) return Error: {error.message};
return ;
};
export default SalesList;
Код: Выделить всё
import { useState, useEffect } from 'react';
import useFetchData from '../services/api/showData';
const UpdateList = () => {
const { data, loading, error, fetchData } = useFetchData();
const [list, setList] = useState([]);
const updateList = async () => {
try {
const newList = await fetchData();
setList([...newList]);
console.log('New list obtained:', newList);
} catch (error) {
console.error('An error occurred while updating your data', error);
}
};
useEffect(() => {
updateList();
}, [fetchData]);
return { list, loading, error, updateList };
};
export default UpdateList;
Код: Выделить всё
import { useState, useEffect, useCallback } from "react";
import axios from 'axios';
const useFetchData = () => {
const [data, setData] = useState([]);
const [loading, setLoading] = useState(false);
const [error, setError] = useState(null);
const fetchData = useCallback(async () => {
setLoading(true);
try {
const response = await axios('http://localhost/REACT/my-app/src/backend/php/api/mostrarDatos.php');
if (!response.data.ok) {
return console.error('An error occurred, please restart. If the issue persists, contact the administrator.');
}
setData(response.data.respuesta);
return response.data.respuesta;
} catch (error) {
setError(error instanceof Error ? error : new Error("An unknown error occurred"));
console.error("Error fetching data:", error);
return [];
} finally {
setLoading(false);
}
}, []);
useEffect(() => {
fetchData();
}, [fetchData]);
return { data, error, fetchData };
};
export default useFetchData;
Подробнее здесь: https://stackoverflow.com/questions/794 ... s-of-table