Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Conditional fetching with Redux-Toolkit RTK-Query

I’m trying to migrate from createAsuncThunks to RTK-Query. On page load I check if there’s no user in store then fetch user and other data from backend.

This code works well with createAsuncThunks but how it should like with RTK-Query?

const InitApp = () => {
  const dispatch = useAppDispatch();
  const user = useAppSelector((state) => state.user);
  const ignore = useRef(false);

  useEffect(() => {
    if (!user && !ignore.current) {
      Promise.all([
        dispatch(getUser()),
         dispatch(getRawMedias()),
        dispatch(getFaces()),
        dispatch(getProjects()),
      ]);
    }

    return () => {
      ignore.current = true;
    };
  }, [dispatch, user]);

  if (!user) {
    return <Loader areaLoader />;
  }

  return <Outlet />;
};

I think this approach is wrong but it’s not clear how to make it properly:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

  const {data} = useGetUserQuery()

  useEffect(() => {
    if (!data) {
      // can't call other hooks here
    }
  }, [data])

>Solution :

Hi you can pass skip parameter, and combine it with initalState like so:

const user = useAppSelector((state) => state.user);
const { data = user } = useUserQuery(undefined, { skip: Boolean(user) });

now this would trigger only if there is no user, and data would be equal to user, if there is user

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading