Full-stack growth with Java, React, and Spring Boot, Half 1

[ad_1]


import './App.css';
import React, { useState, useEffect } from 'react';

operate App() {
  const [todos, setTodos] = useState([]);

  // Fetch todos on element mount
  useEffect(() => {
    fetch('http://localhost:8080/todos')
      .then(response => response.json())
      .then(information => setTodos(information))
      .catch(error => console.error(error));
  }, []);

  // Perform so as to add a brand new TODO merchandise
  const addTodo = (description) => {
    fetch('http://localhost:8080/todos', {
      methodology: 'POST',
      headers: { 'Content material-Sort': 'utility/json' },
      physique: JSON.stringify({ description }),
    })
      .then(response => response.json())
      .then(newTodo => setTodos([...todos, newTodo]))
      .catch(error => console.error(error));
  };

  // Toggle completion
  const toggleTodoComplete = (id) => {
    const updatedTodos = todos.map(todo => {
      if (todo.id === id) {
        return { ...todo, accomplished: !todo.accomplished };
      }
      return todo;
    });
    setTodos(updatedTodos);

    // Replace completion 
    fetch(`http://localhost:8080/todos/${id}`, {
      methodology: 'PUT',
      headers: { 'Content material-Sort': 'utility/json' },
      physique: JSON.stringify({ accomplished: !todos.discover(todo => todo.id === id).accomplished }),
    })
      .catch(error => console.error(error));
  };
  const deleteTodo = (id) => {
    const filteredTodos = todos.filter(todo => todo.id !== id);
    setTodos(filteredTodos);
    fetch(`http://localhost:8080/todos/${id}`, {
      methodology: 'DELETE'
    })
    .catch(error => console.error(error));
  };

We now have capabilities for creation, toggling completion, and deletion. To load the to-dos initially, we use the useEffect impact to name the server for the preliminary set of to-dos when React first hundreds the UI. (See my introduction to React hooks to study extra about useEffect.)

useState lets us outline the todos variable. The Fetch API makes it fairly clear to outline the back-end calls and their handlers with then and catch. The unfold operator additionally helps to maintain issues concise. Right here’s how we set the brand new todos listing:

[ad_2]

Leave a Reply

Your email address will not be published. Required fields are marked *