Tuesday 28 November 2023

Count Increment using React Redux

 We will see below logic step by step

Folder Structure
--Create React App
>npx create-react-app react-demo
>cd react-demo
>code .

--Install below redux plugin
> npm install redux react-redux redux-thunk 

I. In actions/counter.js file and below are code snippets
const INCREMENT = () => (dispatch) => {
    dispatch({ type: "INCREMENT", payload: null });
  };
 
  export { INCREMENT };
 
II. In components/counter.js file and below are code snippets
import React from "react";
import { connect } from "react-redux";
import { INCREMENT } from "../actions/counter";

class Counter extends React.Component {
  handleIncrement() {
    this.props.INCREMENT();
  }

  render() {
    return <button onClick={() => this.handleIncrement()}>Increase</button>;
  }
}

export default connect(null, { INCREMENT })(Counter);

III. In reducers/counter.js file and below are code snippets
const initialState = {
    count: 0
  };
 
  const counterReducer = (state = initialState, action) => {
    switch (action.type) {
      case "INCREMENT":
        return { ...state, count: state.count + 1 };
      case "DECREMENT":
        return { ...state, count: state.count - 1 };
      case "RESET":
        return { ...state, count: 0 };
      default:
        return state;
    }
  };
 
  export default counterReducer;
 
IV. In store/counter.js file and below are code snippets
import { createStore, applyMiddleware } from "redux";
import counterReducer from "../reducers/counter";
import thunk from "redux-thunk";

const store = createStore(counterReducer, applyMiddleware(thunk));

export default store;

V. In App.js file and below are code snippets
import React from "react";
import { connect } from "react-redux";
import { INCREMENT } from "./actions/counter";
import Counter from "./components/counter";

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      test: Math.random() * 10
    };
  }
  render() {
    return (
      <>
        <h1>Count App Test</h1>
        <h3>Random Test: {this.state.test}</h3>
        <h2>Count: {this.props.count}</h2>
        <Counter />
      </>
    );
  }
}

const mapStateToProps = (state) => {
  return {
    count: state.count
  };
};

const mapDispatchToProps = {
  INCREMENT
};

export default connect(mapStateToProps, mapDispatchToProps)(App);

VI. In index.js file and below are code snippets
import { StrictMode } from "react";
import ReactDOM from "react-dom";
import App from "./App";
import { Provider } from "react-redux";
import store from "./store/store";

const rootElement = document.getElementById("root");

ReactDOM.render(
  <StrictMode>
    <Provider store={store}>
      <App />
    </Provider>
  </StrictMode>,
  rootElement
);





No comments:

Post a Comment