I am trying to set up Global State with a few functions that can be exported to other components. Here's my code
import React from 'react';
const initialState: string[] = [];
type ACTIONTYPE = { type: 'add'; payload: string } | { type: 'remove'; payload: string };
export const GlobalContext = React.createContext(initialState);
function reducer(state: string[], action: ACTIONTYPE) {
switch (action.type) {
case 'add':
return [...state, action.payload];
case 'remove':
return [...state.filter(user => user != action.payload)];
default:
throw new Error();
}
}
export const GlobalProvider = ({ children }: { children: React.ReactNode }) => {
const [state, dispatch] = React.useReducer(reducer, initialState);
function increment(user: string) {
dispatch({
type: 'add',
payload: user,
});
}
function decrement(user: string) {
dispatch({
type: 'remove',
payload: user,
});
}
return (
<GlobalContext.Provider value={{ state, increment, decrement }}>
{children}
</GlobalContext.Provider>
);
};
And IntelliSense underlines 'state' inside the value of GlobalContext.Provider saying
Type '{ state: string[]; increment: (user: string) => void; decrement: (user: string) => void; }' is not assignable to type 'string[]'. Object literal may only specify known properties, and 'state' does not exist in type 'string[]'.
How can I resolve this error?