Created
April 3, 2020 14:03
-
-
Save binhtran04/9fc904c8a9f4d07ff1139c2fce077cab to your computer and use it in GitHub Desktop.
Implement markWatchedMovie
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 MoviesContext = React.createContext(); | |
| const MARK_WATCHED_MOVIE = 'MARK_WATCHED_MOVIE'; | |
| const moviesReducer = (state, action) => { | |
| switch (action.type) { | |
| case MARK_WATCHED_MOVIE: { | |
| const movies = state.movies.map(movie => { | |
| if (movie.id === action.payload.id) { | |
| return { ...movie, watched: !movie.watched }; | |
| } | |
| return movie; | |
| }); | |
| return { | |
| ...state, | |
| movies, | |
| }; | |
| } | |
| default: | |
| throw new Error(`Action is not supported: ${action.type}`); | |
| } | |
| }; | |
| export const MoviesProvider = props => { | |
| const [state, dispatch] = React.useReducer(moviesReducer, initialState); | |
| const value = React.useMemo(() => ({ state, dispatch }), [state]); | |
| return <MoviesContext.Provider value={value} {...props} />; | |
| }; | |
| export const useMoviesContext = () => { | |
| const context = React.useContext(MoviesContext); | |
| if (!context) { | |
| throw new Error('useMoviesContext must be used inside a MoviesProvider'); | |
| } | |
| const { state, dispatch } = context; | |
| const { movies } = state; | |
| const markWatchedMovie = id => { | |
| dispatch({ type: MARK_WATCHED_MOVIE, payload: { id } }); | |
| }; | |
| return { movies, markWatchedMovie }; | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment