Home > Net >  Conditional fetching with Redux-Toolkit RTK-Query
Conditional fetching with Redux-Toolkit RTK-Query

Time:12-30

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:

  const {data} = useGetUserQuery()

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

CodePudding user response:

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

  • Related