Search code examples
redux-toolkit

Redux Toolkit - do not send request when query param is invalid


I've checked the redux toolkit docs and don't see an example of this typical use case: do not send the request of the query has an invalid param.

For example, a get request to endpoint /categories/{name} requires a name value. If name does not have a value, then the request should not be made.

const baseQuery = fetchBaseQuery({
  baseUrl: Constants.PATHWAY_API_URL
});

export const pathwayApi = createApi({
  reducerPath: 'pathwayApi',
  baseQuery: baseQueryWithReAuth,
  endpoints: builder => ({
    getSubCategories: builder.query({
      // NETWORK REQUEST SHOULD NOT BE MADE IF "name" param is falsy
      query: name => `${Constants.PATHWAY_API.CATEGORIES_PATH_NAME}/${name}`,
    }),
  }),
});

I want to add this type of param validation to all my queries that require a param value or values. What's the recommended approach / pattern for handling this validation at the createApi (or possibly fetchBaseQuery) layer? Thanks in advance!


Solution

  • You can actually throw an error in your query function.

    export const pathwayApi = createApi({
      reducerPath: "pathwayApi",
      baseQuery: baseQueryWithReAuth,
      endpoints: (builder) => ({
        getSubCategories: builder.query({
          // NETWORK REQUEST SHOULD NOT BE MADE IF "name" param is falsy
          query: (name) => {
            if (!name) {
              throw new Error("Category name is required.");
            }
            return `${Constants.PATHWAY_API.CATEGORIES_PATH_NAME}/${name}`;
          }
        })
      })
    });
    

    When this happens, your hook will have isError: true but no network request will be made. The error property of your hook will be a SerializedError object with properties name, message and stack, which you can use to display the error in your UI.

    This is the same type of error object that you get if you have a TypeError somewhere in your code. Note that JavaScript errors will have error.message while API errors (FetchBaseQueryError) will have error.error.

    const Category = ({ name }) => {
      const { data, error, isError } = useGetSubCategoriesQuery(name);
    
      return (
        <div>
          <h3>Name: "{name}"</h3>
          {isError && (
              <div>{error?.error ?? error?.message}</div>
          )}
        </div>
      );
    };
    

    CodeSandbox Link