Home > Blockchain >  How do I show my todos in React component
How do I show my todos in React component

Time:10-28

Im making a simple todo app with fastapi and react. How do I show my todos? I tried use {todo.data}, but it doesn't work.

That's my Todos.js component:

import React, { useEffect, useState } from "react";

export default function Todos() {
    const [todo, setTodo] = useState([])
    useEffect(() => {
        fetch('http://localhost:8000/todos')
            .then(response => response.json())
            .then(json => setTodo(json))
    }, [])
    return (
        <div>
        <h1>My Todos:</h1>
        <ui>
            <li>
                my todos
            </li>
        </ui>
        </div>
    )
}

here's how http://localhost:8000/todos looks like:

{
   data: [
   {
      name: "buy bread",
      is_done: false,
      id: 1
   },
   {
      name: "clean kitchen",
      is_done: false,
      id: 2
   },
   {
      name: "string",
      is_done: false,
      id: 3
   }
   ]
}

CodePudding user response:

First, you need to map over the returned data. Then, you actually need to render it in your return statement.

import React, { useEffect, useState } from "react";

export default function Todos() {
    const [todo, setTodo] = useState([]);
    useEffect(() => {
        fetch("http://localhost:8000/todos")
            .then((response) => response.json())
            .then((json) => setTodo(json.data));
    }, []);
    return (
        <div>
            <h1>My Todos:</h1>
            <ul>
                {todo.map((todo) => (
                    <li key={todo.id}>
                        {todo.name} <input type="checkbox" checked={todo.is_done} />
                    </li>
                ))}
            </ul>
        </div>
    );
}
  • Related