0.0.4 • Published 3 years ago

context-simplifier v0.0.4

Weekly downloads
-
License
MIT
Repository
github
Last release
3 years ago

context-simplifier

Utility to simplify context api usage in react

NPM JavaScript Style Guide

Install

npm install --save context-simplifier
yarn add context-simplifier

API

createContextProvider(contextName, initialValue, reducerFunction)provider

Creates a context and returns the provider.

ParamTypeDescription
contextNamestring:requiredContext name must be string without any spaces or special characters. Examples: count, countContext
initialValueany:optionalInitial Value for the context
reducerFunctionfunction:optionalReducer function to update context value. Reducer function will receive two params state and action

getContextValue(contextName)contextValue

Creates a context and returns the provider.

ParamTypeDescription
contextNamestring:requiredProvide the context name to fetch its value

getContextAction(contextName)contextSetterFunction

Creates a context and returns the provider.

ParamTypeDescription
contextNamestring:requiredProvide the context name to get its setter function

Usage

To create new context

Use createContextProvider to create new context. It will return the provider for the created context

import React, { Component } from 'react'
import { createContextProvider } from 'context-simplifier'

const App = () => {
  const CountProvider = createContextProvider('count', 0)

  return (
    <>
      <CountProvider>
        <Counter />
        <Layout>
          <CountDisplay />
        </Layout>
      </CountProvider>
    </>
  )
}

To use the context value use getContextValue

import React from 'react'
import { getContextValue } from 'context-simplifier'

const CountDisplay = () => {
  const count = getContextValue('count')

  return <div>{count}</div>
}

export default CountDisplay

To get the setter for updating the context value

Use getContextAction to get the setter function which can be used to update the context value

import React from 'react'
import { getContextAction } from 'context-simplifier'

const Counter = () => {
  const setCount = getContextAction('count')

  const increment = () => {
    setCount((oldValue) => oldValue + 1)
  }

  const decrement = () => {
    setCount((oldValue) => oldValue - 1)
  }

  return (
    <>
      <button onClick={increment}>Increment</button>
      <button onClick={decrement}>Decrement</button>
    </>
  )
}

export default Counter

License

MIT © Harshdand

0.0.3

3 years ago

0.0.4

3 years ago

0.0.2

3 years ago