Created
September 28, 2018 05:15
-
-
Save denismaster/5257bb4d8678cd352d600390aa200dc5 to your computer and use it in GitHub Desktop.
Redux without Redux
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React from 'react'; | |
import ReactDOM from 'react-dom'; | |
import { Subject } from 'rxjs'; | |
import { startWith, scan } from 'rxjs/operators' | |
// create our stream as a subject so arbitrary data can be sent on the stream | |
const action$ = new Subject(); | |
// Initial State | |
const initState = { name: 'Harry' }; | |
// Redux reducer | |
const reducer = (state, action) => { | |
switch (action.type) { | |
case 'NAME_CHANGED': | |
return { | |
...state, | |
name: action.payload | |
}; | |
default: | |
return state; | |
} | |
} | |
// Reduxification | |
const state$ = action$.pipe(startWith(initState), scan(reducer)); | |
// Higher order function to send actions to the stream | |
const actionDispatcher = (func) => (...args) => | |
action$.next(func(...args)); | |
// Example action function | |
const changeName = actionDispatcher((payload) => ({ | |
type: 'NAME_CHANGED', | |
payload | |
})); | |
// React view component | |
const App = (props) => { | |
const { name } = props; | |
return ( | |
<div> | |
<h1>{name}</h1> | |
<input value={name} onChange={(e)=>changeName(e.target.value)}></input> | |
<button onClick={() => changeName('Harry')} >Harry</button> | |
<button onClick={() => changeName('Sally')} >Sally</button> | |
</div> | |
); | |
} | |
// subscribe and render the view | |
const dom = document.getElementById('root'); | |
state$.subscribe((state) => | |
ReactDOM.render(<App {...state} />, dom)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment