AnjaSiewert / Art-gallery-app

https://art-gallery-app-pi.vercel.app
0 stars 2 forks source link

User Story 8: Persist Favorites and Comments in the Browser #8

Open AnjaSiewert opened 1 year ago

AnjaSiewert commented 1 year ago

Value Proposition

As an art enthusiast

I want to persist my favorites and comments

so that the data will not be lost when I close the app.

Acceptance Criteria

Tasks

To use the useImmer hook to mutate the artPiecesInfo state, implement this example to combine both.

Hook:

import produce, { freeze } from "immer";
import { useCallback } from "react";
import useLocalStorageState from "use-local-storage-state";

export function useImmerLocalStorageState(key, options) {
  const [value, setValue] = useLocalStorageState(key, {
    ...options,
    defaultValue: freeze(options.defaultValue),
  });

  return [
    value,
    useCallback(
      (updater) => {
        if (typeof updater === "function") setValue(produce(updater));
        else setValue(freeze(updater));
      },
      [setValue]
    ),
  ];
}

Usage in App component:


import { useImmerLocalStorageState } from "./useImmerLocalStorageState";

export default function App({ Component, pageProps }) {
  const [artPiecesInfo, updateArtPiecesInfo] = useImmerLocalStorageState(
    "art-pieces-info",
    { defaultValue: [] }
  );
  // ...
}