O
O
Orion Orion2022-01-24 19:23:15
JavaScript
Orion Orion, 2022-01-24 19:23:15

How to make a component auto-render after a change in the database?

const { logout } = useAuth();
    const [tasks,setTasks] = useState([]);
    const { id } = JSON.parse(localStorage.getItem('id'));
    const [search,setSearch] = useState('');

   <b> const deleteHandler = async (id) => {
        try {
            await axios.delete(`http://localhost:5000/task/${id}`)
        } catch (error) {
            console.log(error)
        }
    }</b>

    const changeSearch = (e) => {
        setSearch(e.target.value)
    }

    const reviewTasks = async () => {
        await axios.get(`http://localhost:5000/task/`, {params: {id}}).then(response => {
                setTasks(response.data)
            })
    }
    const filterTask = tasks.filter(({task}) => {
        return task.toLowerCase().includes(search.toLocaleLowerCase())
    })

        useEffect( async () => {
            reviewTasks()
        },[])

  return <div>
  
        {tasks&&
                filterTask.map((task) => (
                    <div key={task.id} className="task">
                        <p className='name'>{task.task}</p>
                        <b><p  onClick={() => deleteHandler(task.id)}><Delete  className='delete'/></p></b>
                    </div>
                ))
                }
            <div className="search-div">
            <h3>Search</h3>
                <form onSubmit={e => e.preventDefault()}>
                    <input className='search-inp' type="text" placeholder='Search a Task' onChange={changeSearch}/>
                </form>
            </div>
  </div>;
}


only deletion is shown here!
after deleting or adding a task, you have to press F5 so that the changes are displayed
the same situation with authorization
how to make it all automatically react to changes in the database?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Archi Barrel, 2022-01-25
@Harlock

In useEffect , in the dependency array, you need to put those values, after changes which the component will be re-rendered.
useEffect( async () => {
reviewTasks()
},[ tasks, id ])
ps useEffect is an asynchronous function. async before callback is optional

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question