-1

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()]));
     }
RoboPHP
  • 410
  • 4
  • 12

2 Answers2

1

LocalStorage saves the data is String key/value pairs format, so save before save data convert object in to string using

JSON.stringify(json.data.patient)

On Save

localStorage.setItem('patients',JSON.stringify(json.data.patient))  

On Retrive

let patients = JSON.parse(localStorage.getItem('patients'));

Storing Objects in localStorage

mastermind
  • 1,057
  • 1
  • 8
  • 15
  • i get the error `Unexpected token o in JSON at position 1` at `patientData: JSON.parse(patients)` – RoboPHP Jun 30 '19 at 10:44
0

The LocalStorage API requires that both the key and value of entries stored are of the string type.

You could revise your code so that data saved to local storage is serialised with JSON.stringify() to a string during save, and then deserialised with JSON.parse() to restore the data from a string during load:

componentDidMount()
{
    try {

    /* Attempt to parse data */
    let patients = JSON.parse(localStorage.getItem('patients'));
    if(patients)
    {
        this.setState({
           patientData: patients
        });
    } 
    catch(err) {
       if(err.name === 'SyntaxError') {
        /* If there was an error parsing the data, fetching it
        from server (which has the side effect of saving the data
        into local storage in the required format is successful */
        localStorage.clear();
        this.getPatients();
       }
    }
}

getPatients(){

    return this.fetchPost().then(([response,json]) => {
        console.log(response);
        if(response.status === 200)
        {             
            this.setState({
                patientDetails: json.data.patient
            })

            /* Use JSON.stringify to serialize the data to a string */
            localStorage.setItem('patients',JSON.stringify(json.data.patient))
        }
    })
}
Dacre Denny
  • 29,664
  • 5
  • 45
  • 65
  • i get the error `Unexpected token o in JSON at position 1` at `patientData: JSON.parse(patients)` – RoboPHP Jun 30 '19 at 10:44
  • @RoboPHP just updated answer - does that help? – Dacre Denny Jun 30 '19 at 10:50
  • no, this answer is working just like my code above...in the console.log(patients), i get [object Object],[object Object],[object Object], – RoboPHP Jun 30 '19 at 11:07
  • Seems like bad data stored from earlier development is the potential cause - just updated code with `localStorage.clear();` in the catch block. Let me know if that helps – Dacre Denny Jun 30 '19 at 11:10
  • I am not able to understand why you have `localStorage.clear();` Besides that isn't solving the issue – RoboPHP Jun 30 '19 at 12:11
  • Strange - the idea with `localStorage.clear()` is to reset the store state if the format of whatever there invalid. Can you please tell me what `console.log(localStorage.getItem('patients'))` produces on the console? – Dacre Denny Jun 30 '19 at 19:46