7.6 C
London
Friday, September 13, 2024

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




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

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

  // Fetch todos on part mount
  useEffect(() => {
    fetch('http://localhost:8080/todos')
      .then(response => response.json())
      .then(knowledge => setTodos(knowledge))
      .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': 'software/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': 'software/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’ve 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:

Latest news
Related news

LEAVE A REPLY

Please enter your comment!
Please enter your name here