svelte-previous
    TypeScript icon, indicating that this package has built-in type declarations

    2.0.0 • Public • Published

    svelte-previous-banner

    svelte-previous

    npm version npm downloads license build coverage size

    Svelte stores that remember previous values!

    This allows us to perform actions that depend on previous values, such as transitions between old and new values.

    Installation

    $ npm i -D svelte-previous

    Since Svelte automatically bundles all required dependencies, you only need to install this package as a dev dependency with the -D flag.

    Demo

    Visit the REPL demo.

    Usage

    usePrevious accepts an initial value, and returns a tuple comprising a Writable and a Readable store.

    <script>
      import { usePrevious } from 'svelte-previous';
    
      export let name;
      // current is writable, while previous is read-only.
      const [currentName, previousName] = usePrevious(0);
      // To update the values, assign to the writable store.
      $: $currentName = name;
    </script>
    
    transition from {$previousName} to {$currentName}.

    Options

    usePrevious takes an options object as its second argument.

    numToTrack: number

    By default, usePrevious tracks one previous value.

    To track more than one value, set numToTrack.

    <script>
      const [current, prev1, prev2] = usePrevious(0, { numToTrack: 2 });
    </script>
    
    from {$prev2} to {$prev1} to {$current}.

    requireChange: boolean

    Due to how reactivity is handled in Svelte, some assignments may assign the same value multiple times to a variable. Therefore, to prevent a single value from overwriting all previous values, a change in value is required before the current and previous values are updated.

    Set requireChange = false to change this behaviour.

    <script>
      const [current, previous] = usePrevious(0, { requireChange: false });
    </script>

    isEqual: (a: T, b: T) => boolean

    By default, equality is determined with the === operator. However, === only checks equality by reference when comparing objects.

    Provide a custom isEqual function to compare objects.

    <script>
      const [current, previous] = usePrevious(0, {
        isEqual: (a, b) => a.name === b.name && a.age === b.age,
      });
    </script>

    It is also possible to use lodash.isequal.

    <script>
      import isEqual from 'lodash.isequal';
    
      const [current, previous] = usePrevious(0, {
        isEqual: isEqual,
      });
    </script>

    Install

    npm i svelte-previous

    DownloadsWeekly Downloads

    404

    Version

    2.0.0

    License

    ISC

    Unpacked Size

    10.9 kB

    Total Files

    5

    Last publish

    Collaborators

    • bryanmylee