如何在 "todo app" 中添加项目而不从 api 中刷新页面

how add item in the "todo app" without page refresh from api in react

我想在 API 的列表中添加一个项目,而无需在 React js 中重新加载页面。目前,它适用于页面刷新。我尝试过条件渲染,但无法制作 it.how 我可以制作吗?当用户点击添加按钮时,它应该立即添加到列表中

这是我的代码:

import "./App.css";
import React, { useEffect, useState } from "react";
import axios from "axios";
function App() {
  const [todo, setTodo] = useState([]);

  const [inputText, setInputText] = useState({
    id: "",
    title: "",
  });

  function handleChange(e) {
    setInputText({
      ...inputText,
      [e.target.name]: e.target.value,
    });
  }
  const [status, setStatus] = useState(false);
  async function addItem(e) {
   
    e.preventDefault();
    await axios.post("http://localhost:3333/todos", inputText);
    setStatus(true);
    setInputText("");
  }

  async function getTodo() {
    try {
      const todo = await axios.get("http://localhost:3333/todos");

      // console.log(todo.data)
      setTodo(todo.data);
    } catch (error) {
      console.log("something is wrong");
    }
  }

  useEffect(() => {
    // Update the document title using the browser API
    getTodo();
  }, []);

  return (
    
    
    <div className="container">
      
      <div className="heading">
        <h1>To-Do List</h1>
      </div>

      <div className="form">
        <input onChange={handleChange} type="text" name="title" />
        <button onClick={addItem}>
          <span>Add</span>
        </button>
      </div>
      <div>
        <ul className="user">
          {todo.map((todos) => {
            const { id, title } = todos;
            return <li key={id}>{title}</li>;
          })}
        </ul>
      </div>
    </div>
    
  );
}

export default App;

用axios.post创建todo后,axios会return一个response对象和新创建的todo数据对象:

  async function addItem(e) {
    e.preventDefault();

    const res = await axios.post("http://localhost:3333/todos", inputText);

    console.log("response:", res) // you can log out the res and see the returned data

    setTodo([res.data, ...todo]) // Push to the front of existing todo list

    setStatus(true);
    setInputText("");
  }