Last active
August 4, 2019 03:33
-
-
Save davidbarratt/f3eb75b3b8653a00ca01ed6abca6811f to your computer and use it in GitHub Desktop.
RxJS with React Hook
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
function createSearchSubject() { | |
return (new Subject()).pipe( | |
// Whatever you want to do, but the end result should be an action object. | |
) | |
} | |
const initialState = { | |
search: '', | |
}; | |
function reducer(state, action) { | |
switch (action.type) { | |
case 'CHANGE': | |
return { | |
...state, | |
[action.name]: action.value | |
}; | |
} | |
} | |
function Awesome() { | |
const { current: subject } = useRef(() => createSearchSubject()); | |
const [state, dispatch] = useReducer(reducer, initialState); | |
const handleChange = ({ name, value }) => { | |
dispatch({ action: 'CHANGE', name, value, }); | |
}; | |
useEffect(() => { | |
const sub = subject.subscribe(action => dispatch(action)); | |
return () => sub.unsubscribe(); | |
}, []) | |
useEffect(() => { | |
subject.next(state.search); | |
}, [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