CreateContext Doesn't Accept defaultValue
I'm Trying to Build a Context by Using createContext from the React Api: Import React, { useState, createContext } from 'React'; Export Const Moviecontext =...
I'm trying to build a context by using createContext from the react API:
import React, { useState, createContext } from 'react';
export const MovieContext = createContext();
export const MovieProvider = (props) => {
const [movies, setMovies] = useState(
[
{
original_title: 'name of movie',
poster_path: 'path_to_poster',
id: 1
}
]
);
return (
<MovieContext.Provider value={[movies, setMovies]}>
{props.children}
</MovieContext.Provider>
);
}
export default MovieProvider;
The createContext() function shows this error:
Expected 1 arguments, but got 0.ts(2554) index.d.ts(385, 9): An argument for 'defaultValue' was not provided.
If I make it a string, and pass a string as value the app builds:
export const MovieContext = createContext('');
<MovieContext.Provider value={''}>
{props.children}
</MovieContext.Provider>
What kind of value do I add as a createContext() parameter to make it work with the useState hook? I'm following this guys tutorial and he does it in JS but I'm building my app in TS so it's a bit more strict.
1 Answer
These are the Typescript types, they are described here. There is a comment in the code why this argument should be required, although the documentation doesn't say it is required.
function createContext<T>(
// If you thought this should be optional, see
//
defaultValue: T,
): Context<T>;
In your case will correctly set the default parameter like
type IMovie = {
original_title: string;
poster_path: string;
id: number;
};
type IMovieContext = [IMovie[], React.Dispatch<React.SetStateAction<IMovie[]>>];
export const MovieContext = createContext<IMovieContext>([[], () => null]);
export const MovieProvider = props => {
const [movies, setMovies] = useState<IMovie[]>([
{
original_title: 'name of movie',
poster_path: 'path_to_poster',
id: 1,
},
]);
return <MovieContext.Provider value={[movies, setMovies]}>{props.children}</MovieContext.Provider>;
};