useEffect is not always executed

  javascript, react-router-dom, reactjs

There is a component:

function Blogs(props) {
    const [links, setLinks] = useState([]);

    function getBlogs() {
        const ids = props.ids;
        for (const id of ids) {
            getBlog(id).then(blog => setLinks([...links, <Link to={`/blog/${id}`}>{blog.name}</Link>]));
        }
    }

    async function getBlog(id) {
        let data = await fetch(`${root}/api/blog/${id}`);
        data = await data.json();
        const blog = data.blog;
        return blog;
    }

    useEffect(() => {
        getBlogs();
    }, []);

    return (
        <div className="profile-blogs">
            <div className="a">Блоги</div>
            <div className="b">
                {links}
            </div>
        </div>
    );
}

links is an array with jsx links. Link exported from react-router-dom. The problem is that useEffect is not always executed, that is, often when a component is called, useEffect simply does not work. I have a guess that this is because of react-router-dom’s navigation, as its links do not refresh the page, but I have no idea how to fix this.

Source: Ask Javascript Questions

LEAVE A COMMENT