Reputation: 1172
I've been struggling to declare the TypeScript types of an initial state of a React Context with our errors. It'll store a list of items, and the initial state should be an empty array.
I've tried many options like using an interface instead of a type, using an object to declare the types of items
and setItems
, declaring the type exactly as it's inferred, even trying to bypass de type declaration altogether, and I've finally managed to make it work like this:
type Props = [any, any];
export const ListContext = createContext<Partial<Props>>([]);
export const ListProvider = (props: any) => {
const [items, setItems] = useState([]);
return (
<ListContext.Provider value={[items, setItems]}>
{props.children}
</ListContext.Provider>
);
};
I'm not sure if it's the correct way (using any
doesn't look like it), and I don't fully understand why it works either.
How can I improve it? Thanks in advance.
Upvotes: 7
Views: 4951
Reputation: 9662
This is the way I approach it:
type Item = {
example_prop: number;
};
interface ContextProps {
items: Item[];
setItems: Function;
}
export const ListContext = createContext<ContextProps>({
items: [],
setItems: () => null
});
interface Props {
some_prop: string;
}
export const ListProvider: React.ComponentType<Props> = props => {
const { some_prop } = props; // This is here just to illustrate
const [items, setItems] = useState<Item[]>([]);
return (
<ListContext.Provider value={{ items, setItems }}>
{props.children}
</ListContext.Provider>
);
};
As you can see I'm passing an object through the Context. The initial state of this object is set to an empty array and a function which returns null; these two values will be overriden and won't actually pass but are required.
The Props from the component I included some_prop
, just to serve as an example. Let me know if something is not clear.
Upvotes: 13