Skip to content

Instantly share code, notes, and snippets.

@davidbarratt
Last active August 4, 2019 15:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save davidbarratt/cf21b65f09a257d7005f92e9b6ef9ed9 to your computer and use it in GitHub Desktop.
Save davidbarratt/cf21b65f09a257d7005f92e9b6ef9ed9 to your computer and use it in GitHub Desktop.
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