DEV Community

Cover image for Day 14 of #100DaysOfCode: Redux (use useSelect and useDispatch instead of connect)
Jen-Hsuan Hsieh
Jen-Hsuan Hsieh

Posted on • Edited on

Day 14 of #100DaysOfCode: Redux (use useSelect and useDispatch instead of connect)

Introduction

We have learned Redux on Day 12 (useSelect and useDispatch).
However, it's complex to connect the child component with actions and states. We can use useSelect and useDispatch to connect the child component with global states.

Roles

1.Reducer and actions

  • As same as Day 12
const { combineReducers } = Redux;

//types
const GET_PRODUCTS = 'GET_PRODUCTS';

//reducer
const initState = {
    products: [],
}

const ShoppingCartReducer = (state = initState, action) => {
    switch(action.type) {
        case GET_PRODUCTS:
            return {
                ...state,
                products: action.payload
            }
        default:
            return state; 
    }
} 

const rootReducer = combineReducers({
    products: ShoppingCartReducer
});

//action
const getProducts = () => ({
    type: GET_PRODUCTS, 
    payload: [{
        category: 'food',
        name: 'noodles',
        size:'large',
        price:100      
    },{
        category: 'food2',
        name: 'noodles',
        size:'small',
        price:50      
    },{
        category: 'food',
        name: 'rice',
        size:'large',
        price:120      
    }]
});

Enter fullscreen mode Exit fullscreen mode

2.store

  • As same as Day 12
const { createStore } = Redux;

//store
const store = createStore(
    rootReducer
);
Enter fullscreen mode Exit fullscreen mode

3.Provider and the parent component

  • As same as Day 12
const { Provider} = ReactRedux;

const app = (
    <Provider store={ store }>
        <ContentContainer/>
    </Provider>
);
Enter fullscreen mode Exit fullscreen mode

4.The child component and useSelect, useDispatch

const { useDispatch, useSelector } = ReactRedux;
const selectProducts = (rootState) => rootState.products.products;

//child component
const Content = () => {
    const disPatch = useDispatch();
  disPatch(getProducts());
    return (
        <Menu/>
    )
}

const Menu = () => {
   const products = useSelector(selectProducts);
   return (
        <div className="container menu-container">
            <div className="row">
                {products.map(product => (
                    <MenuItem product = {product}/>
                ))}
            </div>
        </div>
    )
}

Enter fullscreen mode Exit fullscreen mode

Implementations

Articles

There are some of my articles. Feel free to check if you like!

Top comments (0)