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 ToDo App using React Js and Redux | Interview Question

Create a ToDo App using React Js and Redux | Interview Question

In one of my previous post, I had created To Do app using only React Js. But in this post, I am going to show you "how to create a same to do app using React js and Redux ( as state management library )

As we all know, Redux is an open source JavaScript library for managing and centralizing application state. Redux is predictable state container for JavaScript apps.

Following is the UI functionality of the application but using Redux only.


Todo App using React-Redux

Dependency:
To use react-redux with your React Application, install it as a dependency:

npm install react-redux

Sample Code:

A) index.js

import React from 'react';
import ReactDOM from 'react-dom';
import { createStore } from 'redux';
import { Provider } from 'react-redux';
import todoReducer from './reducers';
import App from './App';

const store = createStore(todoReducer);

ReactDOM.render(
  <Provider store={store}>
    <App />
  </Provider>,
  document.getElementById('root')
);


B) App.js

import React, { useState } from 'react';
import './style.css';
import { addToDoremoveToDoupdateToDoremoveAllToDo } from './actions';
import { connect } from 'react-redux';
import AddToDoList from './ToDoList';

const ToDoHeader = () => {
  return <div id="todoHeader"> To Do Application Using React-Redux </div>;
};

const AddToItem = (props=> {
  const { textsetText } = props;
  return (
    <div id="todoAdd">
      <input
        id="todoInput"
        type="text"
        value={text}
        onChange={(e=> {
          setText(e.target.value);
        }}
      />
      <button
        id="save"
        type="submit"
        onClick={() => {
          props.addItem(text);
        }}
      >
        {props.btnName}
      </button>
    </div>
  );
};

const ToDoFooter = (props=> {
  const { clearAll } = props;
  return (
    <div id="todoFooter">
      <button
        type="submit"
        onClick={() => {
          clearAll();
        }}
      >
        Clear All{' '}
      </button>
    </div>
  );
};

function App(props) {
  const [textsetText] = useState('');
  const [btnNamesetBtnName] = useState('Save');
  const [editIdsetEditId] = useState(0);
  const { data } = props;

  const addItem = () => {
    if (btnName == 'Save') {
      props.dispatch(addToDo(text));
    } else {
      props.dispatch(updateToDo(editIdtext));
    }
    setBtnName('Save');
    setEditId(0);
  };

  const deleteTodo = (id=> {
    props.dispatch(removeToDo(id));
  };

  const EditTodo = (id=> {
    setEditId(id);

    const editItem = data.filter((item=> {
      return item.todoId == id;
    });

    let edittedText = editItem[0].todoName;
    setText(edittedText);
    setBtnName('Update');
  };

  const clearAll = () => {
    props.dispatch(removeAllToDo());
  };

  return (
    <div>
      <ToDoHeader />
      <br />

      <AddToItem
        btnName={btnName}
        addItem={addItem}
        setText={setText}
        text={text}
      />
      <br />

      <AddToDoList EditTodo={EditTodo} deleteTodo={deleteTodo} />
      <br />

      {data && data.length > 0 && <ToDoFooter clearAll={clearAll} />}
    </div>
  );
}

const MapStateToProps = (state=> {
  return { data: state };
};

export default connect(MapStateToProps)(App);

C) actions.js

window.id = 0;

export const addToDo = (text=> {
  return {
    type: 'ADD_TODO',
    id: window.id++,
    text,
  };
};

export const removeToDo = (id=> {
  return {
    type: 'REMOVE_TODO',
    id,
  };
};

export const updateToDo = (idtext=> {
  return {
    type: 'UPDATE_TODO',
    id,
    text,
  };
};

export const removeAllToDo = () => {
  return {
    type: 'REMOVE_ALL_TODO',
  };
};

D) reducers.js

const todoReducer = (state = [], action=> {
  switch (action.type) {
    case 'ADD_TODO':
      return [
        ...state,
        {
          todoId: action.id,
          todoName: action.text,
        },
      ];

    case 'REMOVE_TODO':
      const removeElement = [...state].filter((item=> {
        return item.todoId != action.id;
      });
      return removeElement;

    case 'UPDATE_TODO':
      [...state].forEach((v=> {
        if (v.todoId === action.idv.todoName = action.text;
      });
      return state;
    case 'REMOVE_ALL_TODO':
      return [];

    default:
      return state;
  }
};

export default todoReducer;

E) ToDoList.js

import React, { useStateuseEffect } from 'react';
import './style.css';
import { connect } from 'react-redux';

const AddToDoList = (props=> {
  console.log(props);
  const { deleteTodoEditTododata } = props;

  return (
    <>
      <div>
        {data &&
          data.length > 0 &&
          data.map((item=> {
            return (
              <div>
                <div id="todoListItem">
                  <label> {item.todoName} </label>
                </div>
                <div id="todoEditDelete">
                  <button
                    id="delete"
                    type="submit"
                    onClick={() => {
                      deleteTodo(item.todoId);
                    }}
                  >
                    Delete
                  </button>
                  <button
                    id="edit"
                    type="submit"
                    onClick={() => {
                      EditTodo(item.todoId);
                    }}
                  >
                    Edit{' '}
                  </button>
                </div>
              </div>
            );
          })}
      </div>
    </>
  );
};

const MapStateToProps = (state=> {
  console.log('state :' + state);
  return { data: state };
};

export default connect(MapStateToProps)(AddToDoList);

F) style.css

#todoHeader,
#todoFooter {
  width470px;
  height30px;
  border1px solid black;
  text-aligncenter;
  line-height30px;
  background-colororange;
  border-radius10px;
}
#todoListItem {
  width330px;
  height30px;
  border1px solid black;
  background-colorgray;
  border-radius10px;
  border-left-width10px;
  border-left-colorgreen;
  floatleft;
}

#todoEditDelete {
  width120px;
  height30px;
  border1px solid black;
  margin-left350px;
  margin-top10px;
  align-itemscenter;
  justify-contentcenter;
  displayflex;
  border-radius10px;
  background-colorgray;
}

#delete,
#edit,
#save {
  margin-right1px;
  border-radius9px;
}

#todoAdd {
  width470px;
  height30px;
  border1px solid black;
  border-radius10px;
}

#todoInput {
  margin-left10px;
  margin-top5px;
  width370px;
  margin-right10px;
}

G) package.json

{
  "name""react",
  "version""0.0.0",
  "private"true,
  "dependencies": {
    "react""^17.0.2",
    "react-dom""^17.0.2",
    "react-redux""^7.2.6",
    "redux""^4.1.2"
  },
  "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

Create a Shopping Item App using React Js and Xstate

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