1.1.0 • Published 4 years ago

use-deep-state v1.1.0

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

use-deep-state

Custom React hook to manage complex state with a deeply nested object.

NPM JavaScript Style Guide

Install

npm install --save use-deep-state

Usage

import React, { Component } from 'react'
import { useDeepState } from 'use-deep-state'
const Example = () => {
    const initialState = {
        user: {
            name: 'John Cleese',
            age: 30,
            activities: [
                { id: 'WORK', name: 'Working', active: true },
                { id: 'PLAY', name: 'Playing', active: false },
            ],
        },
        verified: false,
    }
    const { state, setState, getStateAt, setStateAt } = useDeepState(initialState)
    const verify = () => {
        setState({ verified: true })
    }
    const goPlay = () => {
        setStateAt(['user', 'activities', activity => activity.id === 'PLAY', 0, 'active'], true)
    }
    return (
        <div>
            <div>
                {state.user.name}, {state.user.age} {state.verified && <span> - Verified</span>}
            </div>
            <br />
            <div>
                <button onClick={verify}>Verify</button> <button onClick={goPlay}>Go play!</button>
            </div>
            <br />
            <div>{getStateAt(['user', 'activities', activity => activity.id === 'PLAY', 0, 'active']) ? <span>Yay, let's play!</span> : <span>Need to work.</span>}</div>
        </div>
    )
}

License

MIT © samirdamle


This hook is created using create-react-hook.