I am trying to have a behaviour similar to the redux' using contextApi
and hooks, but I'm having some trouble with typescript.
I want to provide both the state of my application and the dispatch to be able to access and modify the store from within a component. The issue is that when I use createContext, I still don't have neither the state
nor the dispatch
objects at hand, because I can only call useReducer
inside a React
component. Therefore I was only able to call createContext
declaring that the type of the argument is any
, in order to pass null at that point and pass another dispatch and state later on.
import React, { createContext, useReducer } from 'react';
import reducerAuth, { initialState } from './reducerAuth';
const ContextAuth = createContext<any>(null);
const StateProvider = (
{ children }:{children:JSX.Element},
) => {
const { Provider } = ContextAuth;
const [state, dispatch] = useReducer(reducerAuth, initialState);
return (<Provider value={{ state, dispatch }}>{children}</Provider>);
};
export { ContextAuth, StateProvider };
Is there a way which I can pass state
and dispatch
without having to declare type any
and without having typescript conflicts?
I didn't want to use redux
to achieve all of this, because I want to use native tools, but redux seemed easier, even though very similar.
I tyed to pass the type of the object {state,dispatch}
to create context, the following way:
const [state, dispatch] = useReducer(reducerAuth, initialState);
type UseReducer = {
state: typeof state,
dispatch: typeof dispatch,
}
const ContextAuth = createContext<UseReducer | null>(null);
But in this case I am no longer able to export Context Auth, because it is then created inside the StateProvider
function.