# duck-state

> Auto State Management

Latest version **1.6.25** (published 2023-09-28) · MIT license · 0 weekly downloads

## Install

```sh
npm install duck-state
pnpm add duck-state
yarn add duck-state
bun add duck-state
```

## Health

**Score 15/100 (F)** — status: abandoned.

Positive: no vulnerabilities.

Warnings: low downloads; no types; no esm support.

Negative: abandoned; low maintenance score.

## Facts

| | |
|---|---|
| Version | 1.6.25 |
| Published | 2023-09-28 |
| First published | 2019-07-03 |
| Weekly downloads | 0 |
| License | MIT |
| TypeScript types | none |
| Module format | CommonJS |
| Dependencies | 5 |
| Unpacked size | 120.8 KB |
| Known vulnerabilities | 0 |
| Install scripts | no |
| Author | Sanatan |
| Maintainers | sanatank, satyamdevd |

## Links

- npm: https://www.npmjs.com/package/duck-state
- Repository: https://github.com/tekie-labs/tekie-redux-state-managment
- Homepage: https://github.com/tekie-labs/tekie-redux-state-managment#readme
- Issues: https://github.com/tekie-labs/tekie-redux-state-managment/issues
- npm.io page: https://npm.io/package/duck-state

## Dependencies (5)

- [lodash](https://npm.io/package/lodash.md) ^4.17.11
- [immutable](https://npm.io/package/immutable.md) ^4.0.0-rc.12
- [pluralize](https://npm.io/package/pluralize.md) ^7.0.0
- [@babel/runtime](https://npm.io/package/@babel/runtime.md) ^7.4.4
- [@babel/plugin-proposal-class-properties](https://npm.io/package/@babel/plugin-proposal-class-properties.md) ^7.4.4

## Recent versions

- 1.6.25 (latest) — 2023-09-28
- 1.6.24 — 2023-09-24
- 1.6.23 — 2023-09-24
- 1.6.22 — 2023-07-25
- 1.6.2 — 2023-07-24
- 1.6.1 — 2023-07-20
- 1.5.7 — 2023-07-20
- 1.6.0 — 2022-11-01
- 1.5.1 — 2022-09-30
- 1.5.0 — 2022-09-30
- 1.4.2 — 2021-09-10
- 1.4.1 — 2021-08-27
- 1.4.0 — 2021-07-18
- 1.3.0 — 2020-12-17
- 1.2.12 — 2020-10-29
- … 15 more at https://npm.io/package/duck-state/versions

## README

# Duck State

Duck-state automatically caches and manages backend response into redux state.

### No Action/Reducers Needed

Given a consistent backend, Ideally you will only ever need to write your query. Actions and reducers are handled automatically.

### Installation

`npm install duck-state`

### Core Concepts
#

Duck state is divided in two parts:

##### Extractor:

It reads backend response, and based on a pre-written schema - it extracts nested data into a flat structure, containing two-way mapping. Like this:

From
```js
{
  animals: [
    {
      id: 0,
      legs: 2,
      cats: [
        {
          id: 0,
          name: 'Cat A'
        },
        {
          id: 1,
          name: 'Cat A'
        }
      ]
    }
  ]
}
```

To

```js
{
  animals: [
    id: 0,
    legs: 2,
    cats: [
      {
        id: 0,
      },
      {
        id: 1,
      }
    ]
  ]},
  cats: [
    {
      id: 0,
      name: 'Cat A',
      animals: [{ id: 0 }]
    },
    {
      id: 1,
      name: 'Cat A',
      animals: [{ id: 0 }]
    }
  ]
}

```
##### Merger:

Data extracted from extractor gets merged in State on the basis of `schema` and  `actionType`

##### Keys:

You send a `key` with your queries, which gets assigned to each object in extractedData. If an object is fetched by multiple queries, all keys will be added. If same queries are fetched again and some objects are not fetched in response, their keys will be removed. Once an Object has 0 key. It will be removed from state.

### Setup

`schema.js`
```js
const schema = {
  animals: {
    children: ['cats'],
    alias: ['animal', 'addToAnimal'],
    type: 'arrayOfObjects'
  },
  cats: {
    alias: ['cat'],
    type: 'arrayOfObjects'
  },
}

export default schema
```

`duck.js`
```js
import State from 'duck-state'
import schema from './schema'
import graphqlLib from '../path/to/graphqlLib'

const duck = new State({
  schema,
  graphqlLib,
})

export default duck
```

`store.js`

```js
import { combineReducers, createStor } from 'redux'
import duck from './duck'

export const rootReducer = combineReducers({
  data: duck.reducer
})

const store = createStore(
  rootReducer
)

duck.registerStore(store)

export default store
```

You should see something like this in your redux devtools:

[Insert Redux State screenshot here]

### Writing a query
```js
// Define
const fetchCats = duck.query({
  query: gql`{
    cats {
    	id
        name
    }
  }
  `,
  variables: {
  },
  type: 'cats/fetch',
  key: 'cats'
})

// Call
await fetchCats()
```

### API

#### State
```js
new State({
	schema,
	customInitialState,
	graphqlLib,
}) -> duck
```

#### Arguments

##### `schema`

Defines root level state and their relationships

```js
{
 [fieldName]: {
 	children: ['childName'],
    aliasName: ['fieldNames'],
    type: oneOf('arrayOfObjects', 'object', 'element')
 }
}
```

`fieldName:` Name of the filed.

`childName`: Children field of fieldName.

`type`

- `arrayOfObjects:` Field is collection of objects. New items with different id's will be appended into collection. Objects with existing id's will be updated with new fields and values.
- `object:` Field is a single objects. New item with different id will replace existing state. Object with existing id will update with new fields and values.
- `element:` Field can be anything. It will be replaced every time. 

##### `customInitialState`

Initial state is created based on the schema. It can be altered by passing object of fields to `cutomInitialState`
```
{
 [fieldName]: {
 	...rest
 }
}
```

`fieldName:` Name of the filed.

##### `graphqlLib`


```
const graphqlLib = (query, variable) => returns new Promise({})
```

#### duck

##### Methods

##### `query`: `({ query, variables, type, key, changeExtractedData, overrideAutoReducer }) -> function () { return new Promise() }`

###### Arguments

`query`: GraphQL query.

`variables`: GraphQL query.

`type`: `string` -`'{actionName}/${actionType}`

- `actionName`: `string`

- `actionType` - `oneOf('fetch' | 'add' | 'delete' | 'update')`

---
_Source: https://npm.io/package/duck-state · Machine-readable twin of the npm.io package page. Health data is recomputed on every publish._
