1

If i add the dependency array "fitems" in the dependecy array like its telling me to do, then it causes infinite loop. also if i dont use the spread operator on the array then the warning doesnt show but then the state change doesnt rerender.

Sidebar.tsx

import { useState, useEffect } from "react";
import { Link, useLocation } from "react-router-dom";
import axios from "axios";
import getItems from "./../services/SidebarItems";
import { sidebarInfoUrl } from "./../services/ApiLinks";

function Sidebar() {
  const fItems = getItems();
  const location = useLocation();
  const paths = location.pathname.split("/");
  const [items, setItems] = useState(fItems);

  useEffect(() => {
    axios.get(sidebarInfoUrl).then((response) => {
      const updatedItems = [...fItems]
      updatedItems.forEach((item) => {
        if (item.match === "projects") item.value = response.data.projects;
        else if (item.match === "contacts") item.value = response.data.contacts;
      });
      setItems(updatedItems);
      console.log("here")
    });
  }, []);

  return (
    <div className="sidebar shadow">
      {items &&
        items.map((item) => (
          <Link
            key={item.match}
            to={item.link}
            className={
              paths[2] === item.match ? "sidebar-item active" : "sidebar-item"
            }
          >
            <span>
              <i className={item.icon}></i> {item.title}
            </span>
            {item.value && <div className="pill">{item.value}</div>}
          </Link>
        ))}
    </div>
  );
}

export default Sidebar;

Here is the sidebar items i am getting from getItems().

sidebarItems.ts

const items = () => {
  return [
    {
      title: "Dashboard",
      icon: "fas fa-home",
      link: "/admin/dashboard",
      match: "dashboard",
      value: "",
    },
    {
      title: "Main Page",
      icon: "fas fa-star",
      link: "/admin/main-page",
      match: "main-page",
      value: "",
    },
    {
      title: "Projects",
      icon: "fab fa-product-hunt",
      link: "/admin/projects",
      match: "projects",
      value: "00",
    },
    {
      title: "Contacts",
      icon: "fas fa-envelope",
      link: "/admin/contacts",
      match: "contacts",
      value: "00",
    },
  ];
};

export default items;
antoninislam
  • 117
  • 1
  • 2
  • 9

1 Answers1

1

Thank to AKX. I found my problem. I had to use useMemo Hook so that my getItem() function doesnt cause infinte loop when i add it to dependency array.

const fItems = useMemo(() => {
    return getItems();
  }, []);

instead of

const fItems = getItems();

Another fix is that,
If i dont send the items from SidebarItems.ts as function but as an array then it wont cause the infinte loop even if i dont use useMemo hook.

antoninislam
  • 117
  • 1
  • 2
  • 9