Understanding and Implementing Schemas in Python

Understanding and Implementing Schemas in Python Introduction In the world of programming, particularly in the context of data management and validation, schemas play a vital role. A schema is essentially a blueprint or a predefined structure that defines the expected format, data types, and constraints for a given data entity. In this blog, we will delve into the concept of schemas in Python, exploring what they are, why they are important, and how you can implement them in your projects. What is a Schema? A schema serves as a contract between different components of a system, ensuring that data is consistent, valid, and well-structured. It defines the rules for how data should be organized, what fields it should contain, and what types of values those fields can hold. In essence, a schema acts as a set of rules that data must adhere to in order to be considered valid. Why Are Schemas Important? Data Validation: Schemas provide a way to validate incoming data. When data is received o

Create a Shopping Item App using React Js and Xstate

Create a Shopping Item App using React Js and Xstate ( state management ) 

In this post, we will create a shopping item app using React js and Xstate. Generally, we use redux for state management but in this application, I am going to show you state management with the help of Xstate.

Shopping-Item-App-using-React-Js-and-Xstate
Shopping Item App using React Js and Xstate

Dependency:

 npm install xstate @xstate/react

Folder Structure:



Sample Code:

A) index.js

import React from "react";
import ReactDOM from "react-dom";

import App from "./App";

ReactDOM.render(<App />document.getElementById("root"));

B) App.js

import React from 'react';
import Product from './Product/Product';
import './style.css';
import {ShoppingContextShoppingMachinefrom './State/index'
import { useMachine } from '@xstate/react';

export default function App() {
  const [currentStatessendToMachine] = useMachine(ShoppingMachine);

  return (
    <ShoppingContext.Provider value={[currentStatessendToMachine]}>
    <div id="product">
        <Product />
    </div>
    </ShoppingContext.Provider>
  );
}

C) State/index.js

import { createContext } from 'react';
import { assigncreateMachine } from 'xstate';

export const ShoppingContext = createContext();

window.id = 1;

const addItemsToList = async (contextevent=> {
  let items = {
    id: window.id++,
    productName: event.productName,
    price: event.price,
    quantity: event.quantity,
  };

  return items;
};

export const ShoppingMachine = createMachine({
  id: 'ShoppingCart',
  initial: 'INIT',
  context: {
    shoppingItems: [],
    totalAmount: 0,
    totalItemCount: 0,
  },
  states: {
    INIT: {},
    ADD_ITEMS: {
      states: {
        LOADING: {
          invoke: {
            id: 'addItemToList',
            src: addItemsToList,
            onDone: {
              target: 'SUCCESS',
              actions: assign({
                shoppingItems: (contextevent=> {
                  let item = event.data;
                  return context.shoppingItems.concat(item);
                },
                totalAmount: (contextevent=> {
                  let price = Number(event.data.price);
                  let quantity = Number(event.data.quantity);

                  let totalPrice = context.totalAmount + price * quantity;

                  return totalPrice;
                },
                totalItemCount: (contextevent=> {
                  return context.totalItemCount + 1;
                },
              }),
            },
            onError: {
              target: 'FAIL',
              actions: assign({ error: (contextevent=> event.data }),
            },
          },
        },
        SUCCESS: {},
        FAIL: {},
      },
    },
  },
  on: {
    ADD_SHOPPING_ITEM: {
      target: 'ADD_ITEMS.LOADING',
    },
  },
});

D) Header/Header.js

import React from 'react';

function Header() {
  return <div>Shopping Item App</div>;
}

export default Header;

E) Product/AddProduct.js

import React, { useStateuseContext } from 'react';
import { ShoppingContext } from '../State/index';

function AddProduct(props) {
  const [productNamesetProductName] = useState('');
  const [pricesetPrice] = useState(0);
  const [quantitysetQuantity] = useState(0);

  const [currentStatessendToMachine] = useContext(ShoppingContext);

  const AddItem = () => {
    sendToMachine('ADD_SHOPPING_ITEM', { productNamepricequantity });
  };

  const onChangeProductName = (e=> {
    setProductName(e.target.value);
  };

  const onChangePrice = (e=> {
    setPrice(e.target.value);
  };

  const onChangeQuantity = (e=> {
    setQuantity(e.target.value);
  };

  return (
    <div id="addproduct">
      <label>Product Name</label>
      <input type="text" onChange={onChangeProductName} /> <br />
      <label>Price</label> <br />
      <input type="text" onChange={onChangePrice} />
      <label>Quantity</label>
      <input type="text" onChange={onChangeQuantity} />
      <button id="button" onClick={AddItem}> Add Item </button>
    </div>
  );
}

export default AddProduct;

F) Product/Product.js

import React from 'react';
import Header from '../Header/Header';
import AddProduct from './AddProduct';
import ShowProductList from './ShowProductList';
import ShowTotalProduct from './ShowTotalProduct';

function Product() {
  return (
    <div>
      <div id="header">
        <Header />
      </div>
      <div id="left">
        <div id="addProduct">
          <AddProduct />
        </div>
        <div id="totalProduct">
          <ShowTotalProduct />
        </div>
      </div>
      <div id="right">
        <div>
          <ShowProductList />
        </div>
      </div>
    </div>
  );
}

export default Product;

G) Product/ShowProductList.js

import React, { useContext } from 'react';
import { ShoppingContext } from '../State/index';

function ShowProductList(props) {
  const [currentStatessendToMachine] = useContext(ShoppingContext);

  return (
    <div>
      <div id="tableHeader">
        <div id="column">Sr#</div>
        <div id="column">ProductName</div>
        <div id="column">Price</div>
        <div id="column">Quantity</div>
      </div>
      <div>
        {currentStates.matches('ADD_ITEMS.SUCCESS') &&
          currentStates.context.shoppingItems.map((item=> {
            return (
              <div id="row" key={item.id}>
                <div id="column">{item.id}</div>
                <div id="column">{item.productName}</div>
                <div id="column">{item.price}</div>
                <div id="column">{item.quantity}</div>
              </div>
            );
          })}
      </div>
    </div>
  );
}

export default ShowProductList;

H) Product/ShowTotalProduct.js

import React, { useContext } from 'react';
import { ShoppingContext } from '../State/index';

function ShowTotalProduct(props) {
  const [currentStatessendToMachine] = useContext(ShoppingContext);

  return (
    <div id="totalItemPrice">
      <label>Total Item : {currentStates.context.totalItemCount} </label> <br />
      <label>Total Price : {currentStates.context.totalAmount} </label>
    </div>
  );
}

export default ShowTotalProduct;

I) style.css

#header {
  colorwhite;
  font-weight: blold;
  margin-bottom20px;
  margin-left20px;
}

#product {
  border1px solid black;
  width575px;
  background-colorgray;
  margin-top50px;
  height300px;
}

#right {
  border1px solid black;
  margin-left270px;
  background-colorwhite;
  border-radius10px;
  height250px;
  width275px;
}

#totalProduct {
  border1px solid black;
  width220px;
  background-colorwhite;
  border-radius10px;
  margin-left20px;
  height85px;
}

#left {
  width250px;
  floatleft;
  height250px;
}

#addProduct {
  border1px solid black;
  colorblack;
  width220px;
  height150px;
  background-colorwhite;
  border-radius10px;
  margin-left20px;
  margin-bottom10px;
}

#tableHeader {
  background#000;
  color#fff;
  displaytable-row;
  font-weightbold;
}
#row {
  displaytable-row;
}

#row:nth-child(odd) {
  background-colorgray;
}
#row:nth-child(even) {
  background-colorwhite;
}
#column {
  displaytable-cell;

  padding6px 6px 6px 6px;
  width120px;
}

#addproduct {
  margin6px;
}

#totalItemPrice {
  margin10px;
}

button {
  margin-top3px;
  colorwhite;
  background-colorblue;
}

J) package.json

{
  "name""react",
  "version""0.0.0",
  "private"true,
  "dependencies": {
    "@xstate/fsm""^1.0.0",
    "@xstate/react""^1.6.3",
    "react""17.0.2",
    "react-dom""17.0.2",
    "xstate""^4.28.1"
  },
  "scripts": {
    "start""react-scripts start",
    "build""react-scripts build",
    "test""react-scripts test --env=jsdom",
    "eject""react-scripts eject"
  },
  "devDependencies": {
    "react-scripts""latest"
  }
}


Happy Learning!! Happy Coding!!

Comments

Popular posts from this blog

useNavigate and useLocation hooks react-router-dom-v6

How to implement error boundaries in React Js

Pass data from child component to its parent component in React Js

Localization in React Js

How to fetch data from an API using fetch() method in React Js

How to fetch data using Axios Http Get Request in React Js?

Routing in React using React-Router Version 6

Create a custom calendar in React Js | Interview Question

Environment Setup and Installation for React Js Application