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

Friday, November 6, 2020

Fetch List of Employees in React

Fetch List of Employees in React


List of Employees present at some URI i.e http://127.0.0.1:9091/employee/fetch

[{"id"1001,"name""Dinesh","salary"10000.0},{"id"1002,"name""Kumar","salary"10000.0},{"id"1003,"name""Dinesh","salary"10000.0},{"id"1004,"name""Kumar","salary"10000.0}

] 


React Output:

1001Dinesh10000
1002Kumar10000
1003Dinesh10000
1004Kumar10000


React Code to Fetch this Data:

import React, { useStateuseEffect } from "react";

import UserService from "../services/user.service";


const Employee1 = () => {
  const APIURL = "http://127.0.0.1:9091/employee/fetch";

  const empployee = {
      id: 10013,
      name: "Dinesh",
      salary: 10000.0
  }

  const [empsetEmp] = useState([empployee]);

  useEffect(() => {
      fetchEmployees();
  }, []); // << super important array

  const fetchEmployees = () => {

      fetch(
          `${APIURL}`
      ).then((response=> response.json())
      .then(
        (data=> setEmp(data)
        );

  }

  return (
    <div className="container">
     
  <table>
      {emp.map((emp=> (
                <tr>
                    <td>{emp.id}</td>
                    <td>{emp.name}</td>
                    <td>{emp.salary}</td>
                </tr>
            ))
            }
     </table>
    </div>
  );
};

export default Employee1;

Tuesday, October 20, 2020

Spring Boot Todos App

 Spring Boot Todos App


import React, { useEffectuseState } from "react";

import { Link } from "react-router-dom";
const axios = require("axios").default;

const Todo = () => {
  const APIURL = "http://127.0.0.1:8080/jpa";

  let id = "id";

  const todoobj = {
    id: 11005,
    username: "dinesh",
    description: "Learn Spring Boot ",
    targetDate: "2020-10-05T10:03:31.432+0000",
    done: false,
  };
  const todoPage = {
    "currentPage": 1,
    "totalPages": 10,
    "totalItems": 10,
    "sortField": "description",
    "sortDirection": "desc",
    "recordPerPage": 10,
    "todosList": [todoobj]
  }

  const [todoPsetTodoP] = useState(todoPage);

  const [todossetTodos] = useState([todoobj]);

  const [directionsetDirection] = useState();
  const [sortFieldsetSortField] = useState("id");




  useEffect(() => {
    fetchTodos();
  }, []); // << super important array


  const fetchTodos = () => {
    // let direction = todoP.direction;
    //console.log("Hello 2"+todoP.sortField);

    //  let sortField = todoP.sortField;
    let recordPerPage = todoP.recordPerPage;
    let currentPageNo = todoP.currentPage;
    /*
        "currentPage": 4,
        "totalPages": 5,
        "totalItems": 10,
        "sortField": "description",
        "sortDirection": "desc",
        "recordPerPage": 2,
    */

    fetch(
      `${APIURL}/users/dinesh/todos/v2/${currentPageNo}/${recordPerPage}?sortField=${sortField}&sortDirection=${direction}`
    )
      .then((response=> response.json())
      .then((data=> {
        setTodoP(data)
        setTodos(data.todosList);
        // setDirection(data.sortDirection);
        console.log(data.sortDirection + " " + direction);
        console.log(todoP);
      });

    console.log("fetched");
  }



  const fetchDataSorted = (event=> {
    event.preventDefault();

    let name = event.target.getAttribute('name')
    let value = event.target.getAttribute('value')

    setSortField(value);

    setTodoP((preValue=> {
      console.log(preValue);
      return {
        ...preValue//Spread Operator 
        [name]: value,
      };
    }
    )

    console.log("Hello" + todoP.sortField);
    //  setDirection((direction=="desc"?"asc":"desc"));
    fetchTodos();
  }


  const handleEdit = (event=> {
    let id = event.target.value;
    console.log("value:" + id);

  }



  const handleDelete = (event=> {
    deleteAPI(event);
    fetchTodos();
  }



  const deleteAPI = (event=> {
    let id = event.target.value;

    let username = "dinesh"
    let URI = `${APIURL}/users/${username}/todos/${id}`;
    console.log(URI);
    axios.delete(URI)
      .then((res=> { console.log(res) })
      .catch((err=> { console.log(err) })

  }



  return (
    <>
      <div class="container">
        <h2>Todos</h2>
        <p>
          My Todos List
        </p>
        <table class="table">
          <thead>
            <tr>
              <th onClick={fetchDataSorted} name="sortField" value="id">ID</th>
              <th onClick={fetchDataSorted} name="sortField" value="username">Username</th>
              <th onClick={fetchDataSorted} name="sortField" value="description">Description</th>
              <th onClick={fetchDataSorted} name="sortField" value="targetDate">Targetate</th>

              <th >Is Done</th>
              <th >Edit</th>
              <th >Delete</th>

            </tr>
          </thead>

          <tbody>
            {todos.map((mytodo=> (
              <tr>
                <td>{mytodo.id}</td>
                <td>{mytodo.username}</td>
                <td>{mytodo.description}</td>
                <td>{mytodo.targetDate}</td>
                <td>{mytodo.done}</td>
                <td><button type="button" className="btn btn-warning" value={mytodo.id} onClick={handleEdit}>Edit</button></td>
                <td><button type="button" className="btn btn-danger" value={mytodo.id} onClick={handleDelete}>Delete</button></td>
              </tr>
            ))}
          </tbody>

        </table>
        <hr />
        <button type="button" className="btn btn-warning" value="Add Todos"> <Link to="/AddTodos">Add Todos </Link></button>
      </div>
    </>
  );
};

export default Todo;





Add Todo

import React, { useState } from 'react'
import { useForm } from "react-hook-form";
import TutorialService from '../../services/TutorialService';
import "./AddTodos.css"
import { useHistory } from "react-router-dom";

const AddTodos = () => {
    const { registerhandleSubmitwatcherrors } = useForm();
    const [submittedsetSubmitted] = useState(false);
    let history = useHistory();

    const onSubmit = data => {
        console.log(data)
        data.username = "dinesh";
        TutorialService.create(data)
            .then(response => {
                console.log(response);
                setSubmitted(true);
            })
            .catch(e => {
                console.log(e);
            });
        history.push('/todo')
    };
    console.log(watch("example")); // watch input value by passing the name of it


    const newAddTodo = () => {
        //  setTutorial(initialTutorialState);
        setSubmitted(false);
    };

    return (
        /* "handleSubmit" will validate your inputs before invoking "onSubmit" */
        <div className="container">
            <div className="row">
                <div className="col-md-3"></div>
                <div className="col-md-6">

                    {(submitted) ?
                        <h3>  Data Submitted Successfully</h3> : ""

                    }
                    <h2>Add Todos</h2>
                    <form className="form-group" onSubmit={handleSubmit(onSubmit)}>
                        <label>Description</label> <input type="text" className="form-control" name="description" defaultValue="test" ref={register({ required: truemaxLength: 30 })} />
                        {errors.desciption && <p className="errorP">*This field is required</p>}

                        <label>Target Date</label> <input type="date" className="form-control" name="targetDate" ref={register({ required: true })} />
                        {errors.targetdate && <p className="errorP">*This field is required</p>}

                        <input type="submit" className="btn btn-success" />
                    </form>
                </div>
                <div className="col-md-3"></div>
            </div>
        </div>
    )
}


export default AddTodos
HTTP

import http from "../http-common";

  const create = data => {
    return http.post(`/users/${data.username}/todos`data);
  };

API Call

import axios from "axios";

export default axios.create({
  baseURL: "http://localhost:8080/jpa",
  headers: {
    "Content-type": "application/json"
  }
});

Saturday, October 3, 2020

Install and Use Bootstrap in React

 Install and Use Bootstrap in React

1. Visit: https://www.npmjs.com/package/bootstrap  for Information.

2.  In React Application run npm install bootstrap

3. Use Bootstrap: import in jsx, i.e in App.js 

    import '../node_modules/bootstrap/dist/css/bootstrap.min.css'


Now you can use Bootstrap elements:

Example use Bootstrap Button:

<button className="btn btn-success">Hello</button>


Friday, October 2, 2020

Handling Form Inputs in React in less lines of code

 Handling Form Inputs in React (less lines of code)




import React, { useState } from 'react'

const MyFormObject = () => {

    const USER = {
        id: "1",
        name: "Dinesh",
        salary: 10000
    }

    const [usersetUser] = useState(USER)

    const onSubmitHandler = (event=> {
        event.preventDefault();
        console.log(user)
    }

//handling Form Input 
    const handleInput = (event=> {
        let name = event.target.name;
        let value = event.target.value;
        setUser((preValue=> {
            console.log(preValue);
            return {
                ...preValue//Spread Operator 
                [name]: value,
            };
        }
        )
        console.log(event.target.value)
    }

    return (
   <> //Fragment
    <form onSubmit={onSubmitHandler}>

       UserID:   
<input type="text" name="id" value={user.id} onChange={handleInput} /><br />
       Name 
<input type="text" name="name" value={user.name} onChange={handleInput} /><br />
       Salary 
<input type="text" name="salary" value={user.salary} onChange={handleInput} /><br />
                
<input type="submit" value="Submit" />

    </form>
  </>
    )

}

export default MyFormObject


App.js Code Snippet:

const LearningComponent = () => {
  return (
    <div>
     <h1> Learning Component </h1>
      <MyFormObject />
    </div>
  )
}

export default App;

Create a Digital Clock using HTML and JavaScript

Create a Digital Clock using HTML and JavaScript  <! DOCTYPE html> < html > < head > <...

Followers

Search This Blog

Popular Posts