I'm using useEffect to fetch some data from Trello and set some states. First I grab the card I'm looking for and call setCard and setCardLocation. Everything is working fine. Then I get into my else case and no matter what I do setPublishDate will never be set, the loop continues to run. Why do all of these other hooks work but my last one doesn't? Thanks.
export default 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') ); 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}`); } }); }); } });
useEffect()as @TaghiKhavari says, or just use slug locally within the useEffect -const slug = new URLSearchParams(window.location.search).get('slug').