DEV Community

loading...
Cover image for Day 14 of #100DaysOfCode: Redux (use useSelect and useDispatch instead of connect)

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

jenhsuan profile image Jen-Hsuan Hsieh Updated on ・1 min read

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!

Discussion (0)

pic
Editor guide