How used selectors in redux?

34 views Asked by At

When clicked from the button component, I set the id, then I pass this id into the Redux-Toolkit Query request, but id is initially null. How can I do the check?

// id maybe null
const { id } = useSelector(userSelector)

const { data } = useGetUserQuery({ id });

Maybe props in up level.

1

There are 1 answers

0
Drew Reese On BEST ANSWER

If I'm correct in understanding that you really want to only make query requests for non-null id values then you can use a skip parameter or a skipToken to wait until id is non-null, or truthy.

See Conditional Fetching

const { data } = useGetUserQuery({ id }, { skip: id !== null });

or

import { skipToken } from "@reduxjs/toolkit/query/react";

...

const { data } = useGetUserQuery(id !== null ? { id } : skipToken);

If you don't want the query to run for any falsey id value, e.g. null, undefined, "", 0, etc, then the above can be simplified a bit.

const { data } = useGetUserQuery({ id }, { skip: !id });

or

const { data } = useGetUserQuery(id ? { id } : skipToken);