Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

refresh table with useEffect

Tags:

reactjs

i'm new to react and i have the following problem: useEffect is updating infinite times, but i just want it to update the data when i insert a new record, i would be grateful if someone can correct me.

this is my code:

index.js

import {createUser, getUsers} from '../actions';

const Home = () => {
    const [data, setData] = useState([]);

useEffect(() => {
    async function fetchData(){
        const result = await getUsers();
        setData(result);
        console.log("teste: ", result);
    }
    fetchData();
}, [setData]);

const handleCreateUser = (user) => {
    createUser(user).then((users) => {
    });
};

if i put on the second param useEffect(() => {}, [setData]), it breaks the infinite loop but the table does not update when i insert a new register and I need to use F5.

what am i doing wrong? the create user is working perfectly, i just want to att in the same time the table

like image 347
gabriel graciani Avatar asked Jan 18 '20 19:01

gabriel graciani


2 Answers

In useEffect, without a second parameter (an array of dependencies), your effect will run indefinitely.

If you only want your effect to run only when you create new user, you can make a separate state which then be included to the dependencies of useEffect, call it a refreshKey for example. My suggestion would be:

import {createUser, getUsers} from '../actions';

const Home = () => {
    const [data, setData] = useState([]);
    const [refreshKey, setRefreshKey] = useState(0);

useEffect(() => {
    async function fetchData(){
        const result = await getUsers();
        setData(result);
        console.log("teste: ", result);
    }
    fetchData();
}, [refreshKey]);

const handleCreateUser = (user) => {
    createUser(user).then((users) => {
      // Refresh the effect by incrementing 1
      setRefreshKey(oldKey => oldKey +1)
    });
};
like image 80
Jarvis Luong Avatar answered Sep 22 '22 12:09

Jarvis Luong


You can leave the dependancy array blank so it will run only once.

hope this will help you understand better.

   useEffect(() => {
      doSomething()
    }, []) 

empty dependency array runs Only Once, on Mount

useEffect(() => {
  doSomething(value)
}, [value]) 

pass value as a dependency. if dependencies has changed since the last time, the effect will run again.

useEffect(() => {
  doSomething(value)
}) 

no dependency. This gets called after every render.

like image 34
Shuhad zaman Avatar answered Sep 19 '22 12:09

Shuhad zaman