Add an array of strings in localStorage without escape characters

Viewed 427

I am trying to save an array of strings in localStorage. This is my code:

export const saveComment = (state) => {
  try {
    const commentExisting = localStorage.getItem("comment");
    const comment = commentExisting ? commentExisting.split(", ") : [];
    comment.push(state);
    localStorage.setItem("comment", JSON.stringify(comment));
  } catch (err) {
    console.log(err);
  }
};

After adding a couple of values I get a lot of escape characters:

["[\"[\\\"Some comment\\\"]\",\"another one\"]","one more comment"]

I want it to be like this: ["some comment", "another comment", "one more comment"]

What is wrong with my code?

2 Answers

You need to JSON.parse the result from localStorage.getItem('comment'). That will turn it back into an array that you can use directly instead of splitting on commas.

const saveComment = (state) => {
  try {
    const commentExisting = localStorage.getItem("comment");
    const comment = commentExisting ? JSON.parse(commentExisting) : [];
    comment.push(state);
    localStorage.setItem("comment", JSON.stringify(comment));
  } catch (err) {
    console.log(err);
  }
};

var comment = ["some comment", "another comment", "one more comment"];
localStorage.setItem("comment", JSON.stringify(comment));
var comment = JSON.parse(localStorage.getItem('comment'));

that's it. that's all you need to do.

Related