DEV Community

Cover image for Day 12 of #100DaysOfCode: Create a ReactJS global states manager from Redux
Jen-Hsuan Hsieh
Jen-Hsuan Hsieh

Posted on • Updated on

Day 12 of #100DaysOfCode: Create a ReactJS global states manager from Redux

Introduction

Introduction to Context APIs

Installation

npm i -S redux react-redux redux-thunk redux-devtools-extension
Enter fullscreen mode Exit fullscreen mode

There are few roles from Redux and React-Redux libray

1.Reducer and actions

  • The reducer and actions here do the same thing as the state in React Context APIs.
  • The reducer has to receive the action. It changes the state depends on the type of action.
const { combineReducers } = Redux;

//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
//Get products
const bindActionsToDispatch = dispatch => ({
  getProducts: (data) => dispatch({
            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

  • In Redux, we inject reducers to store
const { createStore } = Redux;

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

3.Provider and the parent component

  • In Redux, we inject store to store
  • We integrate Provider with the parent component
const { Provider} = ReactRedux;

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

4.connect and the child component

const { connect } = ReactRedux;

const bindActionsToDispatch = dispatch => ({
  getProducts: (data) => dispatch({
            type: GET_PRODUCTS, 
            payload:...
       })
})

//child component
const Content = ({products: {products}, getProducts}) => {
  React.useEffect( ()=>{
    getProducts();
    }, []);

    return (
        ...
    )
}

const mapStateProps = state => ({
    products: state.products
});
const ContentContainer = connect( mapStateProps, bindActionsToDispatch)(Content);

Enter fullscreen mode Exit fullscreen mode

These is a simple digram for React components and Context APIs.

Alt Text

Implementations

Articles

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

Top comments (0)