0.2.6 • Published 4 years ago

reduxed-context v0.2.6

Weekly downloads
7
License
ISC
Repository
github
Last release
4 years ago

React context API used to replicate a simpler redux state manager

This package aims to help providing a fast replica of redux state manager with a provider and a hook consumer. Wrap you app/component/page with the Provider and its actions/reducers/initialState, and use the hook consumer in any component below.

Only works with react >=16.8

How to use it

Actions

// context/actions.js
const countActions = (id) => ({
    increment: () => ({id: id, type: 'INCREMENT'}),
    decrement: () => ({id: id, type: 'DECREMENT'}),
    reset: () => ({id: id, type: 'RESET'})
})

export default (id) => ({
    count: countActions(id),
})

Reducers

// context/reducers.js
const countReducer (state, { type }) => {
    switch (type) {
        case 'INCREMENT':
            state++
            return state
        case 'DECREMENT':
            state--
            return state
        case 'RESET':
            return 0
        default:
            return state
    }
}

export default (state, action) => {
    return {
        ...state,
        count: countReducer(state.count, action),
    }
}

Provider

import { Provider } from 'reduxed-context'

// Import your actions and reducers
import actions from '../context/actions'
import reducers from '../context/reducers'

// Your initial provided state
const providedState = { count: 0, isAuth: false}

const YourEnhancedComp = () => <Provider value={ providedState } actions={actions} reducers={reducers}>
    <div> You can use the providedState anywhere below the Provider.</div>
</Provider>

Consumer

import { useCtxActions } from 'reduxed-context'

const YourConnectedComp = () => {
    const [{ count, isAuth }, // First object is the providedState
        { increment, decrement, reset } // Second  object is the reducers
    ] = useCtxActions(['count', 'isAuth'], [['increment', 'decrement', 'reset']]) // First and second array of strings to link the called states and reducers

    return <section>
        <button onClick={ increment }> + </button>
        <div>Count: { count }</div>
        <button onClick={ decrement }> - </button>
        <button onClick={ reset }> Reset </button>
        <hr />
    </section>
}

export default YourConnectedComp
0.2.6

4 years ago

0.2.5

4 years ago

0.2.4

4 years ago

0.2.3

4 years ago

0.2.2

4 years ago

0.2.1

4 years ago

0.2.0

4 years ago

1.0.0

4 years ago

0.1.32

4 years ago

0.1.31

4 years ago

0.1.3

4 years ago

0.1.2

4 years ago

0.1.1

4 years ago

0.1.0

4 years ago