mmalmi.github.io/_posts/2021-9-27-gun-for-react-state-management.md
Martti Malmi 30b45d5f7c .
2021-09-27 11:51:11 +03:00

1.1 KiB
Raw Blame History

layout, title, date, tags, published, description, image
layout title date tags published description image
post Gun.js: The Best Solution for React State Management 2021-9-27 01:37:00 +0000 software true Better alternative to Redux https://siriusbusiness.fi/assets/images/posts/cheesecake.jpg

Fed up with writing a ton of Redux boilerplate just to make a form input editable?

Theres a better alternative: Gun.js. It makes state synchronization and persistence super easy:

// Initialize Gun with options to make sure that the state is synced only locally
const State = new Gun({multicast: false, peers: [], localStorage: true, file: State.local});

class CommentForm {
    componentDidMount {
        State.get(comment).on(comment => this.setState({comment}));
    }
    
    onInput(e) {
        State.get(comment).put(e.target.value);
    }
    
    render() {
        return {
            <form>
                <input type=text value={{this.state.comment}} onInput={e => this.onInput(e)} />
            </form>
        }
    }
}

Now you have a comment form that automatically persists its content.