Firing RTK dispatch after condition is true?

Viewed 55

I have a RTK query that takes a few seconds to fetch the data. When isSuccess is true I am then trying to fire a dispatch.

const router = useRouter();
const num = router.query.id;
const { data, error, isLoading, isSuccess } = useModByIdQuery(num);
const dispatch = useDispatch();

  {
    isSuccess && dispatch(addCurrentMod(data));
  }

The problem with this is it fires multiple times (4 to be exact). I tried putting it in a useEffect but as the data takes a few seconds to fetch the dispatch errors out (as it's undefined).

I am not really sure the best way to approach fixing this?

Thanks.

1 Answers

First of all, given information is not enough to understand what you are trying to do. still I can see your response depends of isSuccess true and if you will console isSuccess you will found multiple true false values, so try get last value only (check for place which are effecting isSuccess API call)

Related