Home > OS >  ReactJS component not re-rendering
ReactJS component not re-rendering

Time:08-24

I have the following component that I want to render if filteredTodos is not empty:

{filteredTodos.lenght > 0 ? (
  <List 
    todos={todos} 
    setTodos={setTodos}
    filteredTodos={filteredTodos}
  /> 
) : <div className="justify-content-center">No tasks have been added, add a new task</div>}

This component tries to renders, only once, and initially the array is empty so my component never renders.

filteredTodos changes based on a useEffect, and it is updating correctly:

useEffect(() => {

    const filterHandler = () => {
        switch(status){
            case "completed": 
                setfilteredTodos(todos.filter(todo => todo.completed === true))
                break;
            case "uncompleted":
                setfilteredTodos(todos.filter(todo => todo.completed === false))
                break;
            default:
                setfilteredTodos(todos);
                break;
        }
    }
    filterHandler();

}, [todos, status]); 

enter image description here

CodePudding user response:

Welcome. Please check the comment I left you regarding showing the addTodo. Looks like the issue could be there.

Regarding the code, some side comments:

Avoid Typos

You can use a linter to help you out with this. length is misspelled here:

{filteredTodos.lenght > 0 ? (

Unique IDS should be unique.

Avoid using random numbers for ids. Despite being highly unlikely, random numbers could eventually be the same. Try to move to a library like uuid.

Readability counts.

setfilteredTodos(todos.filter(todo => todo.completed === false)

could be:

setfilteredTodos(todos.filter(todo => todo.completed) //or
setfilteredTodos(todos.filter(todo => !todo.completed)
  • Related