0

When I open the app, useEffect successfully transfers the data to my app via fetch function and the app re-renders so that the todos are displayed.

If I create a new todo via handleCreateTodo, send it to the server via a post request and then call the fetch function, the database is updated but the app does not Re-Render. I have to refresh the browser manually so that the new todo is displayed.

import { FunctionComponent, ReactElement, ChangeEvent, MouseEvent, useState, useEffect } from "react";

import { v4 } from "uuid";
import axios from "axios";

const endpoint = 'http://localhost:8000';


let currentTodos: Todos  [];  

export const TodoTable: FunctionComponent = (): ReactElement => {
   
   
    const [todos, setTodos] = useState<Array<Todos>>([]);   
    const [enterTodo, setEnterTodo] = useState<string>('');


    //Get Todos from DB
    const fetchTodos = async() => {
        const { data, status } = await axios.get(endpoint + '/todos');
        if(status == 200){
            setTodos(data);
        }
        
    }

    useEffect(() => {
        fetchTodos();
    }, []);


    //Enter Todo handler
    const handleEnterTodo = (event: ChangeEvent<HTMLInputElement>): void => {
      setEnterTodo(event.currentTarget.value);
    };
  

    //Create Todo handler
    const handleCreateTodo = async () => {

        //create new Todo
        const newTodo = {
            //id: todos.length+1,
            id: v4(),
            describtion: enterTodo,
            done: false
        };

        const { status } = await axios.post(endpoint + '/todos', newTodo);
        if(status == 200){
            fetchTodos();
        }
        
        setEnterTodo('');
 
    };

    return(
            <>  
                <div className="todoTable">
                    <InputBar 
                        enterTodo={ enterTodo } 
                        handleEnterTodo={ handleEnterTodo } 
                        handleCreateTodo={ handleCreateTodo }
                        handleClearTodos= { handleClearTodos }
                    />
                    
                    <TodosDisplay 
                        todos={ todos } 
                        handleDeleteTodo={ handleDeleteTodo } 
                        handleStatus={ handleStatus }
                    /> 
                </div>    
            </>      
    );
}
1
  • Did you ever get this figured out? Commented Jul 6, 2023 at 15:37

1 Answer 1

2
useEffect(() => {

},[todos])

If useEffect take parameter on this array, it will render when todos updated.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.