I am able to fetch data from an api. But my page keeps fetching the data from the api whenever the page loads. I tried to solve this issue using localStorage like below.
I try to load the data stored in the localStorage but whenever the data loads, the data appears as [object Object]. How can i get the elements (patient_name,patient_phone) from the response instead of showing [object Object].
PS: Beginner with React
Component
componentDidMount()
{
let patients = localStorage.getItem('patients');
if(patients)
{
this.setState({
patientData: patients
})
console.log(JSON.stringify(patients));
}
else
{
this.getPatients();
}
}
getPatients(){
return this.fetchPost().then(([response,json]) => {
console.log(response);
if(response.status === 200)
{
this.setState({
patientDetails: json.data.patient
})
localStorage.setItem('patients',json.data.patient)
}
})
}
fetchPost(){
const URL = 'http://domain:3000/api/';
return fetch(URL, {method:'GET',headers:new Headers ({
'Accept': 'application/json',
'Content-Type': 'application/json',
.then(response => Promise.all([response, response.json()]));
}