Unable to set state of a different state from a state react after setting that state

Viewed 34

I have visibleItems which a state that is an array of objects that contains a field of technonology and when the page loads I have to set visibleItems to a hardcoded values of objects such as the object below, then I have to create a set from the field of technonology from the array of visibleItems and set a state called technologies but it seems as though technologies cannot be set and appears to always be empty please see debugger photo. I have verified that the set is not empty on the function getTechnologies and think that it is something related about async calls of setState? but I have tried to watch for visibleItems and only call getTechnologies when it updates but no luck.

Any help would be appreciated!

  {
    id: 9,
    title: "Stock Finder",
    category: "front end",
    image: "images/stockfinder.GIF",
    images: [
      "images/1st.png",
      "images/3st.png",
      "images/4st.png",
      "images/2st.png",
      "images/5st.png",
    ],
    content:
      "Stock Finder is a web-based application that allows users to find the current price of a stock in real time.",
    task: "Info",
    technology: ["React.js", "Redux", "API", "Web App", "Heroku"],
    demolink: "fake url/",
    codesource: "fake url",
  },

debugger

  const [getAllItems] = useState(allData);
  const [activeFilter, setActiveFilter] = useState("");
  const [visibleItems, setVisibleItems] = useState([]);
  const [technologies, setTechnologies] = useState([]);
  // eslint-disable-next-line react-hooks/exhaustive-deps
  const getTechnologies = async () => {
    // Implement
    // for each visibleItems create a set that has the technology property

    let temp = new Set();
    for (let i = 0; i < visibleItems.length; i++) {
      for (let j = 0; j < visibleItems[i].technology.length; j++) {
        temp.add(visibleItems[i].technology[j]);
      }
    }
    // why am I not able to set the state?
    setTechnologies(temp);
  };
  useEffect(() => {
    setActiveFilter(filters[0].text.toLowerCase());
    const fetchData = async () => {
      await setVisibleItems(getAllItems);
    };

    fetchData();
  }, []);
  useEffect(() => {
    // not able to set technologies?
    // why is technologies empty?
    // even after watching visibleItems?
    getTechnologies();
    debugger;
  }, [getTechnologies, visibleItems]);
1 Answers

Dont use Set, you should use Array instead

const getTechnologies = async () => {
    let temp = new Set();
    for (let i = 0; i < visibleItems.length; i++) {
        for (let j = 0; j < visibleItems[i].technology.length; j++) {
        temp.add(visibleItems[i].technology[j]);
        }
    }
    setTechnologies([...temp]);
};
Related