Reputation: 65
I am getting a data from the promise and I want to set it in react hook, it does but it makes infinite requests and re-rendering of the page, also I want some specific only data to fill
const [rows, setRows] = useState([]);
useEffect(() => {
async function fetchData() {
myEmploiList({
user: user.id
}).then((data) => {
//setRows(data);
const newData = [];
data.forEach((item, index) => {
newData[index] = {
id: item._id,
name: item.name,
society: item.society
};
setRows(newData);
});
});
}
fetchData();
});
Upvotes: 2
Views: 1375
Reputation: 81
Move setRows
call out of the forEach
loop and include user.id
into the dependency array
const [rows, setRows] = useState([]);
useEffect(() => {
async function fetchData() {
myEmploiList({
user: user.id
}).then((data) => {
//setRows(data);
const newData = [];
data.forEach((item, index) => {
newData[index] = {
id: item._id,
name: item.name,
society: item.society
};
});
setRows(newData);
});
}
fetchData();
}, [user.id]);
Upvotes: 0
Reputation: 2948
You should add dependencies to your useEffect
hook. It is the second argument of this hook.
useEffect(() => {
// your code
}, [deps]);
deps explanation:
For further reading, I highly recommend this blog post.
Upvotes: 6