meeshaa
meeshaa

Reputation: 163

Storing object property in local Storage

I have an app that fetches 30 images, when you hover over the image you can "favorite" the image by clicking on the heart that appears. When the heart is clicked this function runs.

    //toggle favorited on and off
  const toggleFavorite = (id) => {
    const newArr = allPhotos.map((photo) => {
      if (photo.id === id) {
        return {
          ...photo,
          liked_by_user: !photo.liked_by_user,
        };
      }
      return photo;
    });
    setAllPhotos(newArr);
  };

when you click this heart, the function above gets the photo and sets the "liked_by_user" property to the opposite of whatever the value is (either true or false) if its true the heart icon is filled in, if its false the heart is just outlined.

I want to store the "Liked_by_user" property in local storage, that way if the page is refreshed the image "liked_by_user" will still be set to true and the heart icon will still be filed in.

Iv never implemented localStorage before.

I think i'm on the right track, when the heart icon is clicked, local storage does get created but it has the value "undefined"

note - All my images are stored in an array called AllPhotos

      //toggle favorited on and off
  const toggleFavorite = (id) => {
    const newArr = allPhotos.map((photo) => {
      if (photo.id === id) {
        return {
          ...photo,
          liked_by_user: !photo.liked_by_user,
        };
      }
      return photo;
    });

    setAllPhotos(newArr);

*****issue below****
    let ImageToStore = newArr.filter((image) => image.id === id);
    localStorage.setItem("image", JSON.stringify(ImageToStore.liked_by_user));
  };

Any help would be greatly appreciated!

Upvotes: 0

Views: 126

Answers (1)

Shubham Periwal
Shubham Periwal

Reputation: 2248

.filter() returns an array so that's why the "liked_by_user" property is undefined.

Try this:

let ImageToStore = newArr.filter((image) => image.id === id)[0];
localStorage.setItem("image", JSON.stringify(ImageToStore.liked_by_user))

Here you are extracting the first element of the array which is the object which will have liked_by_user property.

NOTE: It'll throw an error if array is null so you may want to add a check for that.

Upvotes: 1

Related Questions