Last active
August 4, 2019 15:52
-
-
Save davidbarratt/cf21b65f09a257d7005f92e9b6ef9ed9 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
const initialState = { | |
search: '', | |
}; | |
function reducer(state, action) { | |
switch (action.type) { | |
case 'CHANGE': | |
return { | |
...state, | |
[action.name]: action.value | |
}; | |
} | |
} | |
function useReactor(reaction, dispatch, inputs = []) { | |
const { current: subject } = useRef(() => reaction(new Subject())); | |
useEffect(() => { | |
const sub = subject.subscribe(dispatch); | |
return () => sub.unsubscribe(); | |
}, []); | |
useEffect(() => { | |
inputs.map(input => subject.next(input)); | |
}, inputs); | |
return subject; | |
} | |
function Awesome() { | |
const [state, dispatch] = useReducer(reducer, initialState); | |
const handleChange = ({ name, value}) => { | |
dispatch({ action: 'CHANGE', name, value, }); | |
}; | |
useReactor(value$ => ( | |
value$.pipe( | |
// Whatever you want to do, but the end result will be passed to the dispatch callback. | |
) | |
), dispatch, [state.search]); | |
return ( | |
<input type="text" name="search" value={state.search} onChange={handleChange} /> | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment