npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

recost

v1.1.0

Published

React context state management system

Downloads

16

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

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

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 - persist/hydrate state using localstorage 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

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

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

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

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

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

import { dispatch } from 'recost'

dispatch(actionObject)

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

actionObject

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

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

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

component

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

const WrappedCount = withState(mapStateToProps)(Count)

or

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

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 for details on our code of conduct, and the process for submitting pull requests to us.

Versioning

We use SemVer for versioning. For the versions available, see the tags on this repository.

Authors

License

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

Acknowledgments