Ecosyste.ms: Awesome

An open API service indexing awesome lists of open source software.

Awesome Lists | Featured Topics | Projects

https://github.com/distolma/immer-svelte


https://github.com/distolma/immer-svelte

Last synced: 16 days ago
JSON representation

Awesome Lists containing this project

README

        

# immer-svelte

[![npm version](https://badge.fury.io/js/immer-svelte.svg)](https://www.npmjs.com/package/immer-svelte)
[![Build Status](https://travis-ci.com/distolma/immer-svelte.svg?branch=master)](https://travis-ci.com/distolma/immer-svelte)

## Installation

```sh
npm i -S immer immer-svelte
```
or
```sh
yarn add immer immer-svelte
```

## API

#### useImmer

The function returns a tuple, the first value of the tuple is the current state, the second is the updater function,
which accepts an [immer producer function](https://github.com/mweststrate/immer#api), in which the `draft` can be mutated freely, until the producer ends and the changes will be made immutable and become the next state.

```html

import { useImmer } from "immer-svelte";

const [state, updateState] = useImmer({ count: 0 });

function increase() {
updateState(draft => {
draft.count++;
});
}

Count: {$state.count}

Increase
```

#### useImmerReducer

```html

import { useImmerReducer } from "immer-svelte";

const initialState = { count: 0 };

function reducer(draft, action) {
switch (action.type) {
case "reset":
return initialState;
case "increment":
return void draft.count++;
case "decrement":
return void draft.count--;
}
}

const [state, dispatch] = useImmerReducer(reducer, initialState);


Count: {$state.count}
dispatch({ type: "reset" })}>Reset
dispatch({ type: "increment" })}>+
dispatch({ type: "decrement" })}>-

```