I have created a page and function to load the customer list. When I add the get method to my code, every time the information is received from the URL and the page is rendered, the get method is called again.
import { useEffect } from "react";
import { api } from "../../../api.js";
import './list.css';
function CustomerList() {
const [customers, setCoustomer] = useState([]);
let ListOfCustomer = [];
useEffect(() => {
console.log('get data from server');
api.get('/Customer', {
auth: { username: 'user', password: 'pass' }
}).then(async function (response) {
await response.data.forEach(element => {
ListOfCustomer.push({
Id: element.id,
CustomerName: element.customerName,
CustomerCode: element.customerCode,
Tel: element.tel,
Mobile: element.mobile,
Connector: element.connector,
AddDate: element.addDate,
});
});
setCoustomer(ListOfCustomer);
}).catch(error => {
console.log("response received: %s ", error);
alert(error.response.data.erro);
console.log("Error received: %s ", error.response.data.erro);
});
});
console.log('read');
return <>
<div className="container">
<div className="row align-items-start">
<h1 className="listTitle">لیست مشتری ها</h1>
</div>
<div className="row align-items-start">
<div className="table-responsive">
<table className="table table-striped table-hover">
<thead className="table-dark">
<tr>
<th scope="col">#</th>
<th scope="col">Customer Name</th>
<th scope="col">Customer Code</th>
<th scope="col">ُTel</th>
<th scope="col">Mobile</th>
<th scope="col">CC</th>
</tr>
</thead>
<tbody>
{
customers.map((o) => {
return <tr key={o.Id}>
<th scope="row">{o.Id}</th>
<td>{o.CustomerName}</td>
<td>{o.CustomerCode}</td>
<td>{o.Tel}</td>
<td>{o.Mobile}</td>
<td>{o.Connector}</td>
</tr>
})
}
</tbody>
</table>
</div>
</div>
</div>
{console.log('read end')}
</>;
}
export default CustomerList;
The api is defined like this, here I replaced the address with ******.
import axios from 'axios'
export const api = axios.create({
baseURL : 'https://******.com/aorBackend/aor.dll'
});
When I delete "useEffect(() => {" and inside it, the page loads once. What to do to solve this problem?
CodePudding user response:
Your useEffect
has no dependencies - that is, it has an empty second argument - so the function will run on every single render.
If you want this to only run on the first render then you should add an empty dependency array as the second argument:
useEffect(() => {
// your function here, calling `api.get`
}, []);
See here for an explanation of this second argument to useEffect
.