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"
  }
});

3 comments:

  1. Coverage on TechHonk delivers timely updates about software trends, gadget innovations, product launches, startup developments, and global technology news, providing modern minds actionable knowledge, meaningful insights, and reliable guidance in the fast-paced tech world.

    ReplyDelete
  2. Journey via TechInMail delivers readers updates about product releases, software trends, gadget innovations, technology news, and digital insights, offering modern minds reliable information, actionable guidance, and clear understanding to stay informed every day.

    ReplyDelete
  3. Discoveries shared by TechPict deliver detailed updates about software developments, gadget releases, product launches, digital stories, and technology trends, providing modern minds meaningful insights, practical knowledge, and expert guidance to navigate emerging tech.

    ReplyDelete

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