I am using useContext react hook, and when I get the context from the useContext, is there a way to access the state?
I might be mixing up things,
here is my global state component
<GlobalContext.Provider
value={{
loadingProducts: state.loadingProducts,
products: state.products,
cart: state.cart,
searchTerm: state.searchTerm,
addProductToCart: addProductToCart,
removeProductFromCart: removeProductFromCart,
showAllProducts: showAllProducts,
showFilteredProducts: showFilteredProducts,
initCatalog: initCatalog,
catalogLoadSuccess: catalogLoadSuccess,
catalogLoadFailure: catalogLoadFailure
}}
>
{props.children}
</GlobalContext.Provider>
and here is my initial state object
const initialState = {
initialProducts: [],
products: [],
cart: [],
searchTerm: '',
loadingProducts: true
};
I have initialized the Global State
const GlobalState = props => {
const [state, dispatch] = useReducer(reducer, initialState);
I want to get to the state object (loadingProducts) from my component and this is how I am getting it.
const context = useContext(GlobalContext);
const {loadingProducts} = context.loadingProducts
Question: Can I access the state directly from context, in my component
ie.
const context = useContext(GlobalContext);
// Or is there an alternative?
const state = context.state
Top comments (1)
@ IDURAR , we use react context api for all UI parts , and we keep our data layer inside redux .
Here Article about : π Mastering Advanced Complex React useContext with useReducer β (Redux like Style) β : dev.to/idurar/mastering-advanced-c...