admin管理员组

文章数量:1356424

How can I update certain properties of a local storage item or object as new data is inputted throughout the user journey and not lose what was previously entered or if the user decides to update?

My journey of 5 containers consisting of asking the user to input the following:

  • Name: string
  • Avatar: integer
  • Favourite Genres: multiple strings

On the first view I have created the local storage object / item that sets the name within the handleSubmit function.

handleSubmit(event) { event.preventDefault();

//Profile object
let profile = { 'name': this.state.name, 'avatar': null, 'genres': '' };

// Put the object into storage
localStorage.setItem('profile', JSON.stringify(profile));

// Retrieve the object from storage
var retrievedObject = localStorage.getItem('profile');

//Log object
console.log('retrievedObject: ', JSON.parse(retrievedObject));

//On form submission update view
this.props.history.push('/profile/hello');

}

On my second view I want to update only the avatar property and maintain what the user had inputted in the previous view.

I'm doing this within the handleSelect function like so:

handleSelect(i) {
    let selectedAvatarId;
    let avatars = this.state.avatars;

    avatars = avatars.map((val, index) => {
      val.isActive = index === i ? true : false;
      return val;
    });

    this.setState({
      selectedAvatarId: selectedAvatarId
    })

    //Profile object
    let profile = { 'avatar': i };

    //Update local storage with selected avatar
    localStorage.setItem('profile', JSON.stringify(profile));
  }

How can I update certain properties of a local storage item or object as new data is inputted throughout the user journey and not lose what was previously entered or if the user decides to update?

My journey of 5 containers consisting of asking the user to input the following:

  • Name: string
  • Avatar: integer
  • Favourite Genres: multiple strings

On the first view I have created the local storage object / item that sets the name within the handleSubmit function.

handleSubmit(event) { event.preventDefault();

//Profile object
let profile = { 'name': this.state.name, 'avatar': null, 'genres': '' };

// Put the object into storage
localStorage.setItem('profile', JSON.stringify(profile));

// Retrieve the object from storage
var retrievedObject = localStorage.getItem('profile');

//Log object
console.log('retrievedObject: ', JSON.parse(retrievedObject));

//On form submission update view
this.props.history.push('/profile/hello');

}

On my second view I want to update only the avatar property and maintain what the user had inputted in the previous view.

I'm doing this within the handleSelect function like so:

handleSelect(i) {
    let selectedAvatarId;
    let avatars = this.state.avatars;

    avatars = avatars.map((val, index) => {
      val.isActive = index === i ? true : false;
      return val;
    });

    this.setState({
      selectedAvatarId: selectedAvatarId
    })

    //Profile object
    let profile = { 'avatar': i };

    //Update local storage with selected avatar
    localStorage.setItem('profile', JSON.stringify(profile));
  }
Share Improve this question asked Jun 5, 2018 at 14:00 FilthFilth 3,22815 gold badges55 silver badges83 bronze badges 2
  • Kind of a side note, but why would you use localStorage through all the process? You have ponent state, which is faster and more reliable. Just set the data on the state of a containe ponent and save it to localStorage once you're finished – SrThompson Commented Jun 5, 2018 at 14:53
  • 1 Great question - unfortunately I didn't set my containers up with a main parent container so they all could share state. The other approach is to setup a store however, this is only a prototype and managed to get this working for now. Thank you! – Filth Commented Jun 5, 2018 at 15:12
Add a ment  | 

2 Answers 2

Reset to default 2

You will need to read the existing value from localStorage, parse it as JSON and then manipulate the data, and write it back. There are numerous libraries out there for easily working with localStorage, but something along the lines of this should work as a generic function:

function updateProfile = (updatedData) => {
    const profile = JSON.parse(localStorage.getItem('profile'));
    Object.keys(updatedData).forEach((key) => {
        profile[key] = updatedData[key];
    });
    localStorage.setItem('profile', JSON.stringify(profile));
}

If you use object spread, it could look a lot cleaner too:

function updateProfile = (updatedData) => {
    const profile = {
        ...JSON.parse(localStorage.getItem('profile')),
        ...updatedData
    };
    localStorage.setItem('profile', JSON.stringify(profile));
}

There should probably be some safety checks in the above code, but hopefully gives you an idea for a starting point.

The only option as far as I know is to get it as a Json, amend accordingly and then save it is again.

本文标签: javascriptReact JS Local Storage update on view changeStack Overflow