Home > Software engineering >  how add item in the "todo app" without page refresh from api in react
how add item in the "todo app" without page refresh from api in react

Time:03-19

enter image description here

I want to add an item on the list from the API without page reload in react js. currently, it works with a page refresh. I have tried with conditional rendering but was unable to make it.how can I make it? when the user click on add button it should instantly add onto the list

here is my code:

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;

CodePudding user response:

After creating todo with axios.post, axios will return a response object and the newly created todo data object:

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