Search This Blog

Showing posts with label React Js. Show all posts
Showing posts with label React Js. Show all posts

Wednesday, 10 January 2024

Quick Tech Bits - React Redux Integration Using Hooks

 Steps to create and integrate Redux Application with React using @reduxjs/toolkit and Hooks

1. To create a redux aware react app, the following installations are required.

2. Create the actions, reducers, store as follows   

Actions > Action.js

 
export const BUY_ICE = 'BUY_ICE';
export const BUY_CHOC = 'BUY_CHOCOLATE'
 
//Create actions
export const buyicecream = () => {
    return {
        type: BUY_ICE
    }
}
 


Reducers > Reducer.js

import { BUY_ICE, buyicecream } from "../Actions/Actions";

const initialState = {
    ice_stock: 100
}

export const purchaseReducer = (prevState = initialState, action) => {
    switch(action.type){
        case BUY_ICE:
           return {
                    ...prevState,
                    ice_stock: prevState.ice_stock-1
                 };
        default:
            return prevState;
    }

}


Store.js

import {createStorefrom 'redux'
import {configureStore, combineReducers} from '@reduxjs/toolkit'
import { purchaseReducer } from '../Reducers/Reducer';
 
const rootreducer = combineReducers({purchaseReducer});
export const shop = configureStore({reducer:rootreducer});
//export const shop = createStore(reducer); //Deprecated...
 


3. Create a react component. In this component import the new hooks "useDispatch", "useSelector". These hooks come from the library 'react-redux'. They perform the task of mapping the redux library's dispatch function to react component, mapping redux store object to react component respectively, as shown in the code below.

In this react component, a button that updates the icecream stock of the redux's store (as created above) is done.

import {useDispatch, useSelector} from 'react-redux';
import { buyicecream } from './Actions/Actions';

export let MyShop = ()=>{

    const dispatchfn = useDispatch();   //redux built-in dispatch fn to dispatch action to redux store thru reducer
    const shopData = useSelector(store => store.purchaseReducer);   //assign redux global store (state obj) to variable
    console.log(shopData);

    return(<>
        <div className='text-primary'>
            Ice cream Stock: {shopData.ice_stock}
        </div>
        <button className='btn btn-primary' onClick= {()=>dispatchfn(buyicecream())}>BUY ICECREAM</button>

    </>);
}


4. Add this to the index js or the route configuration in your react app. This component will be wrapped inside the <Provider> which is provided by 'react-redux' package.

import {shop} from './Store/store' //comes from redux's store created above
import {Provider} from 'react-redux';
import { MyShop } from './ReduxIntegration'; //react component

let ReduxComponent = () =>{
    return (
        <Provider store={shop}>
            <MyShop/>
        </Provider>
    )
}

//In the route configuration add it as follows
export let Container = () => {
    return(
        <BrowserRouter>
            <Routes>                           
                <Route path='/redux' element={<ReduxComponent/>}/>
            </Routes>
        </BrowserRouter>
    )
}


5. Finally add it to the correct virtual DOM in index.js as shown.

Index.js


const root = ReactDOM
                    .createRoot(document
                                  .getElementById('root'));

root.render(
  <React.StrictMode>  
   <Container/>
  </React.StrictMode>
);
To execure, be sure you have navigated to your project directory from command terminal  
          






This completes the integration, using Hooks and the @reduxjs/toolkit

  

When executed, the output should look as follows

CLICK BUY ICECREAM         









Thursday, 3 November 2022

Create and Execute React Js App

 

Pre-requisites:

                                Node Js (https://nodejs.org)

-----------------------------------------------------------------------------------------------------------------------------

1.      Create a react app

 

C:\Your_Directory\>create-react-app <app_name_in_lowercase> 

 

       OR

 

C:\Your_Directory\> npx create-react-app <app_name_in_lowercase>

 

               

        This will seed a react app for you. This react app consists of all dependencies and a project folder structure as shown in the screenshot below



a.       public: This folder contains all the files which can be shared with other files in this project such as images, json files etc

b.       src: This folder is used for react js components and code development

c.       node_modules: This works like the npm’s local registry

d.       The files like .gitignore, package-lock.json, package.json are configuration files

a.       .gitignore: This file contains all the files that should be ignored in case you wish to push your project to github

b.       .package-lock.json, package.json: These files store the dependencies for the react app. In case the node_modules folder is deleted, it can be recovered if package.json is available. The command used to recover node_modules from package.json is

>npm install

 

 

 

2.      Executing a react app

C:\Your_Directory\> > npm start

 

 

a.       This hosts the react app on localhost at port 3000 by default

b.       To pull down this hosted app press on the command prompt Ctrl+C