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
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)
});
};
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With