maher ben abdesslam
maher ben abdesslam

Reputation: 65

How to set value of react hook in promise?

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

Answers (2)

frndmg
frndmg

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

Incepter
Incepter

Reputation: 2948

You should add dependencies to your useEffect hook. It is the second argument of this hook.

useEffect(() => {
// your code
}, [deps]);

deps explanation:

  • no value: will execute effect every time your component renders.
  • []: will execute effect only the first time the component renders.
  • [value1, value2, ...]: will execute effect if any value changes.

For further reading, I highly recommend this blog post.

Upvotes: 6

Related Questions