Home > database >  Add data into Array in local storage, React
Add data into Array in local storage, React

Time:09-15

I'm trying to store the page Id in an array stored in local storage every time a user load a page.

I have my array, it create one if needed but for some reasons it does not update the array in new page load and keeps the first page Id. I want to add the page id in that array on every page load if the id is not already in that array. I've tried a lot of things but it seems like I don't understand something, any help ? Thanks

Here is my code

    const [isPostId, setItems] = useState([postId]);

  useEffect(() => {
//const items = JSON.parse(localStorage.getItem('items'));

if (JSON.parse(localStorage.getItem('isPostId')) == null) {
  localStorage.setItem('isPostId', JSON.stringify(isPostId));

}
if (!isPostId.includes(postId)) {
  JSON.parse(localStorage.getItem('isPostId'))
  localStorage.setItem('isPostId', JSON.stringify(isPostId));
}  },[isPostId]);

EDIT: It works now, looks like I was confused about how localStorage works, now it's clear thanks for your help everyone

Both are working:

  useEffect(() => {
    const storageKey = "isPostId";
    const json = localStorage.getItem("isPostId");
    const previousPosts = json ? JSON.parse(json) : [];
    const filtered = previousPosts.filter((it) => it !== postId);
    const updatedPosts = [...filtered, postId];

    const stringifyed = JSON.stringify(updatedPosts);
    localStorage.setItem("isPostId", stringifyed);
    console.log('heu',filtered)
  }, [])
useEffect(() => {
  // options a - full replace
  localStorage.setItem('isPostId', JSON.stringify(isPostId));

  // option b - only add unique, don't remove previous
  var currentIds = JSON.parse(localStorage.getItem('isPostId')) || [];
  isPostId.map((e) => {
    if (!currentIds.includes(e) {
      currentIds.push(e);
    }
  })
  localStorage.setItem('isPostId', JSON.stringify(currentIds));
}, [isPostId])

CodePudding user response:

Right now the code in the first if statement will put ONE id in local storage if there isn't one already, but not as an array. The code in the second if statement will also only set one id. You need to be setting an array value as shown below

If isPostId is declared as an array:

useEffect(() => {
  // options a - full replace
  localStorage.setItem('isPostId', JSON.stringify(isPostId));

  // option b - only add unique, don't remove previous
  var currentIds = JSON.parse(localStorage.getItem('isPostId')) || [];
  isPostId.map((e) => {
    if (!currentIds.includes(e) {
      currentIds.push(e);
    }
  })
  localStorage.setItem('isPostId', JSON.stringify(currentIds));
}, [isPostId])

If isPostId is declared as a string:

If you are certain there will not be single string values in localStorage and there will only be null values or arrays, you can do this as such:

useEffect(() => {
  var currentIds = JSON.parse(localStorage.getItem('isPostId')) || [];

  if (!currentIds.includes(isPostId) {
    currentIds.push(isPostId);
  }

  localStorage.setItem('isPostId', JSON.stringify(currentIds));
}, [isPostId])

If there is a possibility that there could be individual string values, you will need an additional check for the code inside the useEffect

var currentIds = JSON.parse(localStorage.getItem('isPostId'));

if (!currentIds?.length) {
  currentIds = [];
} else if (typeof currentIds !== 'object') {
  // value in localStorage is a single string/number rather than an array
  currentIds = [currentIds]
);

if (!currentIds.includes(isPostId) {
  currentIds.push(isPostId);
}

localStorage.setItem('isPostId', JSON.stringify(currentIds));

Could simplify the second chunk further if desired

CodePudding user response:

If I understood the question correctly, then you need something like this solution.

useEffect(() => {
    const storageKey = "isPostId";
    const json = localStorage.getItem("isPostId");
    const previousPosts = json ? JSON.parse(json) : [];
    const updatedPosts = [...previousPosts, ...isPostId];
    const uniquePosts = Array.from(new Set(updatedPosts))
    const stringifyed = JSON.stringify(uniquePosts);
    localStorage.setItem("isPostId", stringifyed);
}, [])
  • Related