Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Step 1:
- // Create an actions and a reducers folder. Then add an index.js file in both folders.
- ************************************************
- // Step 2:
- // @ Root of application create a <config>.js file.
- import { createStore } from 'redux';
- import reducer from './src/reducers';
- const configRedux = () => createStore(reducer);
- export default configRedux;
- ************************************************
- // Step 3:
- // Import configRedux() into index.js and wrap <App />
- import configRedux from '../configRedux';
- import { Provider } from 'react-redux';
- const store = configRedux();
- // Here you'll wrap App in the ReactDOM render
- <Provider store={store}> <App/> </Provider>
- // Don't worry... The app is freaking out because we haven't built the reducer yet.
- ************************************************
- // Step 4
- // @/actions/index.js
- // You'll want to export const any actions then wrap that variable into a function.
- export const ACTION_NAME = "ACTION_NAME";
- // This is known as the action creator.
- export const actionName = payload => ({
- type: ACTION_NAME,
- payload: payload
- });
- ************************************************
- // Step 5
- // @/reducers/newReducer
- // Create a new reducer and import actions from appropriate action file; in this case it's index.js
- import { ACTION_NAME } from "../actions/index.js";
- const initialState = {
- date: Date.now()
- };
- const newReducer = (state = initialState, action) => {
- switch (action.type) {
- case ACTION_NAME:
- return {
- ...state,
- date: action.payload
- };
- default:
- return state;
- }
- };
- export default newReducer;
- // Now that it's exported, import it into @/reducers/index.js. Add to the combineReducers function in the export default.
- ************************************************
- // Step 6
- // @/reducers/index.js
- import { combineReducers } from 'redux';
- import newReducer from '../reducers/newReducer';
- // You'll also need to import any other necessary custom reducers.
- export default combineReducers({
- newReducer
- // Include any other reducers required by your application.
- });
- ************************************************
- // Step 7
- // How to consume the data using hooks within a functional component.
- // ! RFCE --> Tab for a new functional component if you're using ES7 extension in VS Code.
- import React from "react";
- import { useDispatch, useSelector } from "react-redux";
- import { actionName } from "../actions/index.js";
- const NewComponent = props => {
- const store = useSelector(state => state.newReducer);
- const dispatch = useDispatch();
- return (
- <div>
- <span>{store.date}</span>
- <button onClick={() => dispatch(actionName(`${Date.now()}`))}>
- Change Date
- </button>
- </div>
- );
- };
- export default NewComponent;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement