Dan
Dan

Reputation: 159

How to save variables to localStorage in ReactJs

I'd like to know how to save a variable's value to localStorage.

I recently learned how to do it in JavaScript, but how do I do it in ReactJs?

Upvotes: 0

Views: 5498

Answers (2)

Umair Ahmed
Umair Ahmed

Reputation: 577

You can use localStorage and its methods to save data to the local storage. Please see: window.localStorage

A very good and informative article is https://www.robinwieruch.de/local-storage-react/

// To save the item
localStorage.setItem('email', JSON.stringify(this.state.UserEmail))
  .then(() => console.log('saved email successfully'))
  .catch(err => console.error('something went wrong', err));

// To retrive that item
AsyncStorage.getItem('email')
.then(val => {
  if (val !== null) console.log(val); // You can do whatever you want with the email
})
.catch(err => console.error(err)) // if there was an error fetching data

Please note that if there is nothing in the localStorage, it would return 'null' so in order to handle errors you need to put them in the if statement and not in catch

Upvotes: 0

Rutul Patel
Rutul Patel

Reputation: 693

you can use something like this to store and load your variables to local storage.

export const loadState = (state) => {

    try {
        const serializedState = localStorage.getItem(state);
        if(serializedState === null){
            return undefined;
        }
        return JSON.parse(serializedState);
    } catch (err) {
        return undefined;
    }
};

export const saveState = (state) => {
    try{
        const serializedState = JSON.stringify(state);
        localStorage.setItem('state', serializedState);
    } catch (err){
        return undefined;
    }
}

Upvotes: 1

Related Questions