# recost

> React context state management system

Latest version **1.1.0** (published 2022-11-16) · MIT license · 0 weekly downloads

## Install

```sh
npm install recost
pnpm add recost
yarn add recost
bun add recost
```

## Health

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

Positive: has types; no vulnerabilities.

Warnings: low downloads; no esm support.

Negative: abandoned; low maintenance score.

## Facts

| | |
|---|---|
| Version | 1.1.0 |
| Published | 2022-11-16 |
| First published | 2018-05-14 |
| Weekly downloads | 0 |
| License | MIT |
| TypeScript types | bundled |
| Module format | CommonJS |
| Dependencies | 0 |
| Unpacked size | 17.5 KB |
| Known vulnerabilities | 0 |
| Install scripts | no |
| GitHub stars | 4 |
| Author | João Moura |
| Maintainers | jwebcoder |
| Keywords | js, react, context, state |

## Links

- npm: https://www.npmjs.com/package/recost
- Repository: https://github.com/JWebCoder/recost
- Homepage: https://github.com/JWebCoder/recost#readme
- Issues: https://github.com/JWebCoder/recost/issues
- npm.io page: https://npm.io/package/recost

## Alternatives

- [@mapbox/jsonlint-lines-primitives](https://npm.io/package/@mapbox/jsonlint-lines-primitives.md) — 5.3M weekly downloads
- [reftools](https://npm.io/package/reftools.md) — 3.5M weekly downloads
- [@hey-api/openapi-ts](https://npm.io/package/@hey-api/openapi-ts.md) — 3.5M weekly downloads
- [@mapbox/geojson-rewind](https://npm.io/package/@mapbox/geojson-rewind.md) — 2.4M weekly downloads
- [turbo-stream](https://npm.io/package/turbo-stream.md) — 1.7M weekly downloads

## Recent versions

- 1.1.0 (latest) — 2022-11-16
- 1.0.2 — 2020-11-06
- 1.0.1 — 2020-02-13
- 0.2.0 — 2019-11-27
- 0.1.6 — 2019-07-30
- 0.1.5 — 2019-07-30
- 0.1.3 — 2019-06-06
- 0.1.2 — 2019-04-04
- 0.1.1 — 2019-03-13
- 0.1.0 — 2018-10-28
- 0.0.2 — 2018-05-14
- 0.0.1 — 2018-05-14

## README

# Recost

React context state management system

## Getting Started

These instructions will get you a copy of the project up and running on your local machine for development and testing purposes.

### Installing

Use **yarn** or **npm** to install the package in your React Application

    yarn add recost

### Usage

Next you need to **initialize the context** with a **reducer** for your application.

#### index.js

```js
import React from 'react'
import ReactDOM from 'react-dom'
import App from './App'
import initContext, { Provider } from 'recost'

// create a reducer function
const reducer = (state, action) => {
  if (action.type === 'COUNT') {
    return {
      ...state,
      count: state.count + 1
    }
  }

  return state
}

// define the initial state for the application
const initialState = {
  count: 1
}

// initialize the context
initContext(initialState, reducer)

ReactDOM.render(
  <Provider> // add the Provider component to your application
    <App/>
  </Provider>,
  document.getElementById('root')
)
```

Now you can use the dispatcher and the state anywhere in the code

#### App.js

```js
import React, { Component } from 'react'
import { dispatch, withState } from 'recost'

let Count = (props) => {
  return <p>{props.count}</p>
}

const mapStateToProps = (state) => ({
  count: state.count
})

Count = withState(mapStateToProps)(Count)

class App extends Component {
  onClickButton() {
    dispatch({
      type: 'COUNT'
    })
  }

  render() {
    return (
      <div>
        <Count/>
        <button onClick={this.onClickButton}>
          Increase
        </button>
      </div>
    )
  }
}

export default App
```

## Using middleware

### Available middleware

[recost-persist](https://github.com/JWebCoder/recost-persist) - persist/hydrate state using localstorage
[recost-logger](https://github.com/JWebCoder/recost-logger) - logs state changes when in development mode

### Create your own

In this example we have added two middleware functions.

A **logger**, that will run **before** and **after** the state changes logging the changes.

#### logger.js

```js
const before = (state, action) => {
  console.log('State before action:', state)
  console.log('Full action:', action)
}

const after = (state, action) => {
  console.log('State after action:', state)
}

export {
  before,
  after
}
```

And a **callAPI**, that runs **before** each state change.

#### callAPI.js

```js
const before = (state, action, dispatch) => {
  if (action.type === 'COUNT_API') {
    setTimeout( // simulates and api call
      () => {
        dispatch({
          type: 'SUCCESS_COUNT'
        })
      }
      , 1000
    )
  }
}

export {
  before
}
```

Now we just need to add the new middleware to the context

#### index.js

```js
import React from 'react'
import ReactDOM from 'react-dom'
import App from './App'
import initContext, { Provider } from 'recost'
import * as logger from './Context/logger'
import * as callAPI from './Context/callAPI'

// create a reducer function
const reducer = (state, action) => {
  if (action.type === 'COUNT') {
    return {
      ...state,
      count: state.count + 1
    }
  }

  return state
}

// define the initial state for the application
const initialState = {
  count: 1
}

// initialize the context with the middleware
initContext(initialState, reducer, [
  logger,
  callAPI
])

ReactDOM.render(
  <Provider> // add the Provider component to your application
    <App/>
  </Provider>,
  document.getElementById('root')
)
```

## API definition

### initContext

Creates a new application context

```js
import initContext from 'recost'

initContext(initialState, reducer, middleware)
```

| Params       | required | description                                                               |
| ------------ | -------- | ------------------------------------------------------------------------- |
| initialState | yes      | initial application state                                                 |
| reducer      | yes      | function that generates new state based on actions                        |
| middleware   | yes      | Array of middleware that can run before or after the reducer taking place |

#### initialState

Defaults to an empty object `{}`

#### reducer

```js
const reducer = (state, action) => {
  if (action.type === 'COUNT') {
    return {
      ...state,
      count: state.count + 1
    }
  }

  return state
}
```

| Params | description                                     |
| ------ | ----------------------------------------------- |
| state  | current application state                       |
| action | action object passed by the dispatcher function |

#### middleware

Defaults to an empty array `[]`

### dispatch

Dispatches an action that will trigger a state change

```js
import { dispatch } from 'recost'

dispatch(actionObject)
```

| Params       | required | description                                                       |
| ------------ | -------- | ----------------------------------------------------------------- |
| actionObject | yes      | object containing the type of action and the payload if necessary |

#### actionObject

```js
dispatch({
  type: 'COUNT',
  payload: null // this property is only required if we want to pass in some data
})
```

### withState

Composed function that takes a mapStateToProps function and a component

```js
import { withState } from 'recost'

WrappedComponent = withState(mapStateToProps)(Component)
```

| Params          | required | description                                                                                                                 |
| --------------- | -------- | --------------------------------------------------------------------------------------------------------------------------- |
| mapStateToProps | no       | function that receives the full state and return a portion of it, if not defined, the entire state is sent to the component |
| component       | yes      | component to wrap with state                                                                                                |

#### mapStateToProps

```js
const mapStateToProps = (state) => ({
  count: state.count
})
```

#### component

```js
const Count = (props) => {
  return <p>{props.count}</p>
}

const WrappedCount = withState(mapStateToProps)(Count)
```

or

```js
class Count extends React.[PureComponent|Component] {
  render() {
    return <p>{this.props.count}</p>
  }
}

const WrappedCount = withState(mapStateToProps)(Count)
```

### Provider

Provider component, sets where we want to deliver our context

```js
import React from 'react'
import ReactDOM from 'react-dom'
import { Provider } from 'recost'

ReactDOM.render(
  <Provider>
    <App/>
  </Provider>,
  document.getElementById('root')
)
```

## Contributing

Please read [CONTRIBUTING.md](CONTRIBUTING.md) for details on our code of conduct, and the process for submitting pull requests to us.

## Versioning

We use [SemVer](http://semver.org/) for versioning. For the versions available, see the [tags on this repository](https://github.com/your/project/tags).

## Authors

-   **João Moura** - _Initial work_ - [JWebCoder](https://github.com/JWebCoder)

<!--
See also the list of [contributors](CONTRIBUTORS.md) who participated in this project.
-->

## License

This project is licensed under the MIT License - see the [LICENSE.md](LICENSE.md) file for details

## Acknowledgments

-   Inspired by [Statty](https://github.com/vesparny/statty) and [Redux](https://redux.js.org/)

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