score:1

Accepted answer
useEffect(() => {
  if (!performedFetch && slug) {
    fetch(
      `https://api.trello.com/1/lists/${listId}/cards?key=${key}&token=${token}`
    )
      .then((response) => response.json())
      .then((data) => {
        setPerformedFetch(true)

      // Note: if there can be only ONE matching card
      const index = data.findIndex((card) => card.desc.includes(slug))
      if (index > -1) {
        const card = data[index]
        setCard(card)
        setCardLocation(index + 1)
        const name = card.name
        const frontHalf = name.split('/')[0].split(' ')
        const month = frontHalf[frontHalf.length - 1]
        const day = name.split('/')[1].split(')')[0]
        setPublishDate(`${month}/${day}`)
      }

      // Setting State in a LOOP? is a problem
      /*
      data.forEach((card, index) => {
        if (card.desc.includes(slug)) {
          setCard(card)
          setCardLocation(index + 1)
        } else if (!publishDate && index > cardLocation) {
          const name = card.name
          const frontHalf = name.split('/')[0].split(' ')
          const month = frontHalf[frontHalf.length - 1]
          const day = name.split('/')[1].split(')')[0]
          setPublishDate(`${month}/${day}`)
        }
      })*/

    })
  }
}, [slug, performedFetch])

score:1

function Home(props) {
  const [performedFetch, setPerformedFetch] = useState(false);
  const [slug, setSlug] = useState(null);
  const [cardLocation, setCardLocation] = useState(1);
  const [card, setCard] = useState(null);
  const [publishDate, setPublishDate] = useState(null);

  const key = ""; // imagine these are here
  const token = "";

  useEffect(() => {
    setSlug(new URLSearchParams(window.location.search).get("slug"));
  });

  useEffect(() => {
    console.log(slug)
    if (!performedFetch && !!slug) {
      fetch(`https://api.trello.com/1/lists/${listId}/cards?key=${key}&token=${token}`)
          .then(response => response.json())
          .then(data => {
            setPerformedFetch(true);

            data.forEach((c, index) => {
              if (c.desc.includes(slug)) {                    
                setCard(c)
                setCardLocation(index + 1)
              } else if (!publishDate && index > cardLocation) { 
                console.log(publishDate); // why is this always null?? also runs multiple times

                const name = c.name;
                const frontHalf = name.split("/")[0].split(" ");
                const month = frontHalf[frontHalf.length - 1];
                const day = name.split("/")[1].split(")")[0];
                setPublishDate(`${month}/${day}`);
              }
            });
        });
    }
  }, [slug, performedFetch])
}

Related Query

More Query from same tag