Last active
April 3, 2020 14:28
-
-
Save binhtran04/fec6ba2a280b0b56ce34913e1ead2191 to your computer and use it in GitHub Desktop.
Skeleton for MovieContext
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
/** | |
initialMovies = [ | |
{ | |
id: uuidv4(), | |
title: 'The Godfather', | |
year: 1972, | |
watched: false, | |
}, | |
{ | |
id: uuidv4(), | |
title: 'Inception', | |
year: 2010, | |
watched: false, | |
}, | |
... | |
] | |
*/ | |
import { initialMovies } from './initialState'; | |
// Create a context with by calling React.createContext() | |
const MoviesContext = React.createContext(); | |
// initial reducer | |
const moviesReducer = (state, action) => { | |
return state; | |
}; | |
/** | |
state can contain more such as a loading status, and error state. e.g. | |
{ | |
status: 'loading', | |
movies: [], | |
error: null, | |
} | |
*/ | |
const initialState = { | |
movies: initialMovies, | |
}; | |
// Create a custom MoviesProvider for the context | |
export const MoviesProvider = props => { | |
const [state, dispatch] = React.useReducer(moviesReducer, initialState); | |
// useMemo to optimize the context value | |
const value = React.useMemo(() => ({ state, dispatch }), [state]); | |
return <MoviesContext.Provider value={value} {...props} />; | |
}; | |
// Custom hook useMoviesContext | |
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; | |
return { movies }; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment