Open Khandagale-Saurabh opened 1 year ago
import React from 'react'; import ReactDOM from 'react-dom'; import App from "./App"; import { createStore } from "redux"; import { composeWithDevTools } from "redux-devtools-extension";
//default state var defaultState = 0;
//action types const ADD_MONEY = "ADD_MONEY"; const WITHDRAW = "WITHDRAW";
//action creators const deposit = (amount) => { return { type: ADD_MONEY, payload: { amount: amount } } };
const withdraw = (amount) => { return { type: WITHDRAW, payload: { amount: amount } } };
//reducers const balanceReducer = (state = defaultState, action) => { console.log("reducer invoked", action); switch (action.type) { case ADD_MONEY: return state + action.payload.amount; case WITHDRAW: return state - action.payload.amount; default: return state; } };
//store var store = createStore(balanceReducer, composeWithDevTools()); store.subscribe(() => { console.log(store.getState()); //get updated state });
//dispatch //dispatch: pass an action to store; it invokes the reducer automatically
store.dispatch(deposit(1000)); //1000
store.dispatch(deposit(450)); //1450
store.dispatch(withdraw(250)); //1200
ReactDOM.render(
Store: it is a place where state is stored Reducer: it is function that take old state and action to be performed on state usually we write this cases in switch cases Subscribe: it will be called every time when state is being changed dispatcher : it is a function where we decide what cases to be performed/called store.dispatch({ type: "withdraw" })
payload : data to be passed instead of action in in reducer
import React, { useState, useContext, useEffect } from 'react'
import { useCallback } from 'react' import DataRead from './dataRead' import {composeWithDevTools} from 'redux-devtools-extension'
import { Reducer } from 'react' import { createStore } from 'redux'
let globalData = 0;
let balance = (state = globalData, action) => { console.log('reduxer invoke', action); switch (action.type) { case 'Deposite': return state + 100; case 'withdraw': return state - 100; default: return state; } }
var store = createStore(balance,composeWithDevTools()); console.log(store.getState());
store.dispatch({ type: "withdraw" }) console.log(store.getState());
store.dispatch({ type: "Deposite" }) console.log(store.getState()); store.dispatch({ type: "Deposite" }) console.log(store.getState());
const AppProvider = ({ children }) => { return (<> Data </>) }