skip to Main Content

I’m working on a React Todo App where I’m using React Router to navigate between different routes. I’ve encountered an issue that I’m struggling to resolve.

Problem:
When I navigate to the edit route (/todos/:id), the page loads infinitely and doesn’t display the expected content. The initial data fetching seems to work fine, but the rendering of the UpdateCard component is causing the problem.

Expected Behavior:
Upon clicking the "Edit" button, I want to be taken to the edit route (/todos/:id) and see a card component similar to the AddTodo component. This card should allow me to update the title and description of the todo item. I have already implemented my backend which has the logic to delete , add and update todo.

Current Behavior:
Instead of displaying the expected card component, the page is stuck in an infinite loading loop.

Steps I’ve Taken:

  • I’ve confirmed that the initial data fetching using Axios works as
    expected.
  • The EditTodo component uses the useParams hook to fetch the
    specific todo’s data.
  • I’ve checked the console for any error
    messages, but there are no errors displayed.

Code:
Here’s a simplified version of the relevant code:

// App.jsx

import React, { useEffect, useState } from "react";
import { Routes, Route } from 'react-router-dom';
import './App.css'
import TodoList from "./TodoList";
import axios from "axios";
import AddTodo from "./AddTodo";
import EditTodo from "./EditTodo";
import 'tachyons';

/// hook
function App() {
  const [todos, setTodos] = useState([]);

useEffect(() => {
    fetch("http://localhost:3000/todos", {
      method: "GET"
    })
    .then((response) => response.json())
    .then((data) => setTodos(data))


    setInterval(() => {
      fetch("http://localhost:3000/todos", {
        method: "GET"
      }).then((response) => {
        response.json().then((data) => {
          setTodos(data);
        })
      });
    }, 10000)
    
  }, []);

  const handleDelete = async(todoId) => {
    await axios.delete(`http://localhost:3000/todos/${todoId}`);
    const response = await axios.get("http://localhost:3000/todos");
    const data = response.data;
    setTodos(data);
  };

  return (
    <div>

      <div className="tc">
        <h1>TodoRobots </h1>
      </div>

      <Routes>
      <Route path="/todos" element={
        <>
        
        <div>
          <AddTodo />
        </div>

        <div>
          <TodoList todos={todos} onDelete={handleDelete} />
        </div>

        </>
      } />

    
        <Route path="/todos/:todosId" element={<EditTodo  todos={todos} setTodos={setTodos} />} />
      </Routes>


    </div>
  );
}


export default App;

//EditTodo.jsx

import { Button, Card, CardActions, CircularProgress, TextField } from "@mui/material";
import axios from "axios";
import { useEffect, useState } from "react";
import { useParams } from "react-router-dom";

function EditTodo() {
    let {todosId} = useParams();
    const [todo, setTodo] = useState("");
    
    useEffect(() => {
        axios.get(`http://localhost:3000/todos/${todosId}`,{
            method: "GET",
        }).then(res => 
            {
                console.log("Todo response:", res.data);
                setTodo(res.data.todo)
            })
    }, []);

    if(!todo){
        return <div style={{display: "flex", justifyContent: "center"}}>
              <CircularProgress />
        </div>
    }

    return <div className="tc">
         <UpdateCard todo={todo} todosId={todosId} />
    </div>

}

    function UpdateCard({todo, todosId}) {

        const [title,setTitle] = useState(todo.title);
        const [description, setDescription] = useState(todo.description);

        return  <div style={{ display: "flex", flexWrap: "wrap", justifyContent: "center", alignItems: "center" }}>
        <div className='tc br3 ma2 grow bw2 shadow-5'>
            <Card style={{ width: 300,  minHeight: 200, padding: 8 , backgroundColor:"#9eebcf"}} >
                <div>
                <TextField
                    onChange={(e) => {
                        setTitle(e.target.value);
                    }}
                    label="Title"
                    variant="outlined"
                    fullWidth
                    style={{ marginTop: 16 }}
                /> 

                <TextField
                    onChange={(e) => {
                        setDescription(e.target.value);
                    }}
                    label="Description"
                    variant="outlined"
                    fullWidth
                    style={{ marginTop: 16 }}
                />
                
                <CardActions style={{ display: "flex", justifyContent: "center", marginTop: 20 }}>
                <Button
                    variant="contained"
                    size="large"
                    onClick={ async () =>{
                        await axios.put(`http://localhost:3000/todos/${todosId}`, {
                            title: title,
                            description: description
                        });
                        alert("Todo updated successfully");
                    } 
                }
                    >Update Todo</Button>
                </CardActions>
                
                </div>     
            </Card>
        </div>
    </div>
}


export default EditTodo;

I would appreciate any guidance on how to resolve this issue. Why is the page loading infinitely when I navigate to the edit route, and how can I fix it? Is there something I’m missing or any suggestions for debugging?

2

Answers


  1. I think, you are using todoId, in the updateCard component without passing it into it.

    function UpdateCard({todo}) {}
    

    But you are using it inside the function.

    function UpdateCard({todo}) {...
    

    Can you check in the handleDelete function. You should better wrap it inside try-catch block and also, do try using timeout for the requests inside the code.

    Login or Signup to reply.
  2. Can you check in the handleDelete function. You should better wrap it inside try-catch block and also, do try using timeout for the requests inside the code.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search