50

From what I am experiencing so far, it doesn't seem like ReactJS updates with the state of localStorage. My code below.

var Frr = React.createClass({
getInitialState: function(){
return { lights: localStorage.getItem('state')}
},

switchoff: function(){
this.setState({lights: localStorage.setItem('state', 'off')}); 
},

switchon:function(){
this.setState({lights: localStorage.setItem('state', 'on')}); 
},

render:function(){
if (this.state.lights === 'on'){ return (
<div>
<p>The lights are ON</p>
<input type="submit" value="Switch" onClick={this.switchoff}/>
</div>
);}

if ( (this.state.lights === 'off')|| (!this.state.lights) ){ return (
<div>
<p>The lights are OFF</p>
<input type="submit" value="Switch" onClick={this.switchon}/>
</div>
);}


}
});

Simple application. If the state of localstorage is off or empty, then render the view with the ON button. If localstorage is on, then render the view with the OFF button.

I want to be able to set this render based on the state of localStorage. I have tried doing the same thing using basic booleans, and it works as expected. However, when using localStorage, something doesn't appear to work.

I wouldn't be surprised if my logic is simply off.

EDIT: To explain, the button and the view don't act as they should. When the lights are off and there is nothing in Storage, the button adds ON to localStorage, but does not change the view. If I refresh the page, the page renders ON, and when I click on it the button works by turning it OFF. But it only works once, which leads me to believe there may be a problem with the OFF switch.

1
  • 4
    something doesn't appear to work -- what doesn't appear to work, and in what way? Commented Jul 17, 2016 at 16:00

8 Answers 8

56

The .setItem() local storage function returns undefined. You need to perform the local storage update and then return the new state object:

switchoff: function(){
    localStorage.setItem('state', 'off');
    this.setState({lights: 'off'}); 
},
Sign up to request clarification or add additional context in comments.

Comments

10

Here is just another Example:

import React from 'react'
class App extends React.Component {
  constructor(props) {
    super(props);
    var storedClicks = 0;

    if (localStorage.getItem('clicks')) {
      storedClicks = parseInt(localStorage.getItem('clicks'));
    }

    this.state = {
      clicks: storedClicks,
    };
    this.click = this.click.bind(this);
  }

  click() {
    var newclick = this.state.clicks + 1;
    this.setState({clicks: newclick});
    // Set it
    localStorage.setItem('clicks', newclick);
  }

  render() {
    return (
      <div>
        <h2>Click the button a few times and refresh page</h2>
        <button onClick={this.click}>Click me</button> Counter {this.state.clicks}
      </div>
    );
  }
}
export default App;

Comments

6

These 4 methods u can use.

// setter
localStorage.setItem('myData', data);
// getter
localStorage.getItem('myData');
// remove
localStorage.removeItem('myData');
// remove all
localStorage.clear();

2 Comments

In React, I have this exact code and after running it's still empty: localStorage.setItem("test", "test");
I needed to add "window." to the beginning of each of the methods in order for them to work.
2

Use please reactjs-localstorage

import {reactLocalStorage} from 'reactjs-localstorage';

reactLocalStorage.set('var', true);
reactLocalStorage.get('var', true);
reactLocalStorage.setObject('var', {'test': 'test'});
reactLocalStorage.getObject('var');

1 Comment

no need to use third party lib, since there's a default one
2

I have written a post regarding this question with some extra information regarding when you should use localStorage:

https://levbuchel.com/react-localstorage/


Original answer:

Your data is determined and saved by pairs of key and value.

Here is an example of how we can add, get and remove such values:

// Add items
localStorage.setItem("theme", "dark");
localStorage.setItem("zoom", "5");
localStorage.setItem("font", "18");

// Get an item
var userTheme = localStorage.getItem("theme");

// Remove an item
localStorage.removeItem("theme");
localStorage.removeItem("font");

Comments

1

React/Typescript/localStorage

You can create a hook to make it more fun to work with localStorage.

import { useEffect, useState } from 'react';

export const useLocalStorage = (storageKey: string, fallbackState: any) => {
  const [value, setValue] = useState<any>(fallbackState);
  const [error, setError] = useState<any>();

  useEffect(() => {
    try {
      const getItemValue = JSON.parse(
        localStorage.getItem(storageKey) as string
      );
      if (getItemValue) {
        setValue(currentValue);
      }
    } catch (e) {
      setError(e);
    }
  }, [storageKey]);

  useEffect(() => {
    try {
      localStorage.setItem(storageKey, JSON.stringify(value));
    } catch (e) {
      setError(e);
    }
  }, [fallbackState, storageKey, value]);

  return { value, setValue, error };
};

Usage

const defaultValue = {
  name: 'John Doe',
  location: 'New York',
}

const {
  value
  setValue
  error,
} = useLocalStorage('local-storage-key', defaultValue);

value contains the current localStorage value for key local-storage-key.

You can use setValue to set a new value

And error returns any error that was returned from the catch in the hook.

Comments

0

You can use use-local-storage-state. Handling all edge-cases when dealing with localStorage is actually hard.

I created the library one year ago and have been maintaining it for the entire time.

Comments

-1
const { data } = response;

const userData = data.user;
// Token Save to local Storage

const access = JSON.stringify(data.tokens);
const refresh = JSON.stringify(data.tokens);

localStorage.setItem('accessToken', access);
localStorage.setItem('refreshToken', refresh);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.