Skip to content

Instantly share code, notes, and snippets.

@binhtran04
Created April 3, 2020 14:03
Show Gist options
  • Select an option

  • Save binhtran04/9fc904c8a9f4d07ff1139c2fce077cab to your computer and use it in GitHub Desktop.

Select an option

Save binhtran04/9fc904c8a9f4d07ff1139c2fce077cab to your computer and use it in GitHub Desktop.
Implement markWatchedMovie
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