Whirlwind991
Whirlwind991

Reputation: 495

Using ReactJS to store array items across multiple pages

I have a navigation component built in React with the constructor that looks like this:

constructor(props) {
    super(props);

    var BCList_store = localStorage.getItem('SelectedOption')
    const BCList = [];

        BCList.push({
            name: document.title             
        });        

    this.state = {
        BCList          
    };
    this.setState({ BCList });
    localStorage.setItem('SelectedOption', JSON.stringify(BCList));       
} 

The idea is that each time the user loads a page, the localStorage is called with the array, the page title is pushed to the array, the state is updated and then the localStorage saves the array with new values.

However when a new page is loaded the array still gets cleared and only one array item (the current page title) appears. Am I using the localStorage incorrectly or is there another way this should be done? Thanks

Upvotes: 1

Views: 799

Answers (1)

Atul
Atul

Reputation: 430

you need to understand two things here

  1. when you set/get the item to/from local storage that should be a string. so when you set array to local storage thats get converted to string you can check it by printing localStorage.getItem('SelectedOption').

    1. you are overiding the key with the new value , so need to append the new value with the previous one.

    constructor(props) { super(props);

    let newArray=[], previousArray = localStorage.getItem('SelectedOption') ;
    if(previousArray){
        newArray = JSON.parse(previousArray);
    }
    const BCList = [];
    
     BCList.push({
            name: document.title             
     });        
    
    this.state = {
        BCList          
    };
    
    // push the current item 
    newArray.push({
            name: document.title             
     });
    
    this.setState({ BCList });
    localStorage.setItem('SelectedOption', JSON.stringify(newArray));          
    

    }

Upvotes: 2

Related Questions