I'm trying post some data in mongodb database and it works perfectly until the fetch request is sending continuously even if I didn't do anything. In the network tab, it shows 200 status firstly but then pending and gives error.
const [services, setServices] = useState([]);
const [treatment, setTreatment] = useState(null);
fetch('http://localhost:5000/services')
.then(res => res.json())
.then(data => setServices(data));
The error is giving after adding the following code:
const booking = {
treatmentId: _id,
treatment: name,
date: formattedDate,
slot,
patientEmail: user.email,
patient: user.displayName,
phone: e.target.mobile.value
}
fetch('http://localhost:5000/booking', {
method: 'POST',
headers: {
'content-type': 'application/json'
},
body: JSON.stringify(booking)
}).then(res => res.json())
.then(data => {
console.log(data, 'success');
toast('Appointment has been set!!!');
})
The following error occurs:
bundle.js:701 GET http://localhost:5000/services net::ERR_INSUFFICIENT_RESOURCES
AppointmentSchedules @ bundle.js:701
renderWithHooks @ bundle.js:53492
updateFunctionComponent @ bundle.js:57611
beginWork @ bundle.js:59578
beginWork$1 @ bundle.js:64465
performUnitOfWork @ bundle.js:63626
workLoopSync @ bundle.js:63539
renderRootSync @ bundle.js:63508
performConcurrentWorkOnRoot @ bundle.js:62805
workLoop @ bundle.js:75228
flushWork @ bundle.js:75202
performWorkUntilDeadline @ bundle.js:75486
bundle.js:701 Uncaught (in promise) TypeError: Failed to fetch
at AppointmentSchedules (bundle.js:701:3)
at renderWithHooks (bundle.js:53492:22)
at updateFunctionComponent (bundle.js:57611:28)
at beginWork (bundle.js:59578:20)
at beginWork$1 (bundle.js:64465:18)
at performUnitOfWork (bundle.js:63626:16)
at workLoopSync (bundle.js:63539:9)
at renderRootSync (bundle.js:63508:11)
at performConcurrentWorkOnRoot (bundle.js:62805:78)
at workLoop (bundle.js:75228:38)
Note: The server side is okay and working without any error
CodePudding user response:
useEffect with no dependency only run on first render
const [services, setServices] = useState([]);
const [treatment, setTreatment] = useState(null);
useEffect(() => {
fetch('http://localhost:5000/services')
.then(res => res.json())
.then(data => setServices(data));
}, [])
CodePudding user response:
When fetching apis in react, you should use useEffect or useLayoutEffect. See useEffect or useLayoutEffect