DEV Community

Cover image for Creating Favourites with Local Storage and useRef() in React.
Vicky Vasilopoulou
Vicky Vasilopoulou

Posted on Edited on

Creating Favourites with Local Storage and useRef() in React.

Hello folks!

I was working on a task the other day and thought would be great to share my experience on building favouriting that is saved on localStorage when the component isClicked.

Hope you enjoy.

Ingredients:

  • npm package react-use-localstorage
  • useRef
  • theme-ui
  • TypeScript
  • full heart icon
  • empty heart icon
  • You can find the icons on iconmonstr -> https://iconmonstr.com/

Process

The idea is to create a Favourite.tsx re-usable component so that we can add it wherever we wanton our project.

NOTE: The npm package is replacing completely the localStorage API.

The idea is that every time I click any Person component to be added on my local storage.

Details:

  • The id is referred to an individual props - in my case is referred to the unique id of each person of a list of many people.
  • JSON.parse(storageItem) is our initialValue.
  • setStorageItem is a function that basically will push the current storageItem to the [].
  • I am using the JSON.stringify() method since the useLocalStorage is accepting strings.
  • useRef() works perfectly since after you re-render the component it will remember the how many items you stored on your local storage.
  • If is favourited(when we click the IconButton) then push that item to the storage if not then remove it.
  • We are using the indexOf() since we don't know each time the item we clicked in which index position is every time, and then with the splice method we remove it.
  • Now if is clicked and favourited then show the full heart otherwise the empty heart.
export interface FavouriteProps {
  id: string
}

export const Favourite = ({
  id,
}: FavouriteProps): JSX.Element | null => {
  const [storageItem, setStorageItem] = useLocalStorage(
    'DFX-favourites',
    JSON.stringify([]),
  )
  const storagedArray = useRef(JSON.parse(storageItem))
  const isFavourited = storagedArray.current.includes(id)

  const handleToggleFavourite = (): void => {
    if (!isFavourited) {
      storagedArray.current.push(id)
      setStorageItem(JSON.stringify(storagedArray.current))
    } else {
     const indexFavouritedId = storagedArray.current.indexOf(id)
      storagedArray.current.splice(indexFavouritedId, 1)
      setStorageItem(JSON.stringify(storagedArray.current))
    }
  }
  return (
    <IconButton
      onClick={handleToggleFavourite}
    >
      {isFavourited ? (
        'Add here your full heart icon'
      ) : (
        'Add here your empty heart icon'
      )}
    </IconButton>
  )
}
Enter fullscreen mode Exit fullscreen mode

The on the code you want to pass the component:

<Favourite id={id} />
Enter fullscreen mode Exit fullscreen mode

Top comments (2)

Collapse
 
nixonthiyagesh profile image
Nixonthiyagesh

Can i use it without useref?

Collapse
 
onlineaid profile image
Online Aid

How we can add more items ?