Fetch not working on first click of onClick function

Viewed 48

When I use modalOpen in a onClick function it wont fetch api on the 1st click causing the code to break but it will on 2nd click what can cause it

// get anime result and push to modal function

const modalAnime = async () => {
  const { data } = await fetch(`${base_url}/anime/${animeId}`)
    .then((data) => data.json())
    .catch((err) => console.log(err));
  SetAnimeModalData(data);
};

I am trying to get the fetch to work on the first click but it doesn't until second or third click

const modalOpen = (event) => {
  SetAnimeId(event.currentTarget.id);
  SetModalVisible(true);

  modalAnime();
  console.log(animeId);
};
const modalClose = () => {
  SetModalVisible(false);
  SetAnimeId("");
};

return (
  <div className="app">
    <Header
      searchAnime={searchAnime}
      search={search}
      SetSearch={SetSearch}
      mostPopular={mostPopular}
      topRated={topRated}
    />
    {loadingState ? (
      <ResultLoading />
    ) : (
      <Results
        animeResults={animeResults}
        topRated={topRated}
        mostPopular={mostPopular}
        modalOpen={modalOpen}
      />
    )}
    {modalVisible ? <AnimeInfoModal modalClose={modalClose} /> : <></>}
  </div>
);

the modal opens fine but the ID isn't captured until the second or third click

I have more code but Stack Overflow won't let me add it.

1 Answers

SetAnimeId() won't update the animeId state property until the next render cycle. Seems like you should only update the visible and animeId states after you've fetched data.

You should also check for request failures by checking the Response.ok property.

// this could be defined outside your component
const fetchAnime = async (animeId) => {
  const res = await fetch(`${base_url}/anime/${animeId}`);
  if (!res.ok) {
    throw res;
  }

  return (await res.json()).data;
};
const modalOpen = async ({ currentTarget: { id } }) => {
  // Await data fetching then set all new state values
  SetAnimeModalData(await fetchAnime(id));
  SetAnimeId(id);
  SetModalVisible(true);
};
Related