3. Query params

Lets take a look at another big part of @42.nl/react-url called: useQueryParams. It fixes the query params are strings and optional problem, via one simple abstraction: useQueryParams. useQueryParams is a React hook which makes all query params typed and makes sure that all query params exist by default. This way you will never need to do null checks to prove to TypeScript that the query param exists.

Lets look at an example of useQueryParams:

import React from 'react';
import { RouteComponentProps } from 'react-router-dom';
import { useQueryParams } from '@42.nl/react-url';

type UserListPathParams = {}

/* Here we define the query params for the UserList component */
type UserListQueryParams = {
  page: number;
  query: string;
  active: boolean;
}

/* 
  Here we define a function which provides the default query params.
  It is used to fill in the blanks when query params are missing.
  This guarantees that they are always filled!

  The reason this is a function is to prevent accidental re-use
  of the same object.
*/
export function defaultUserListQueryParams(): UserListQueryParams {
  return {
    page: 1,
    query: '',
    active: false,
  };
}

/* 
  By extending RouteComponentProps we get the standard props that
  react-router adds when the component in a route.
*/
export default function UserList() {
  const location = useLocation();

  const queryParams = useQueryParams({
    /* We give it the location which contains the raw query param string. */
    location,
    /* Provide the default query params which fill in the blanks. */
    defaultQueryParams: defaultUserListQueryParams(),
    /* When an error occurs the `debugName` is shown in the message. */
    debugName: 'UserList',
  });

  /* 
    Because we have defined default query parameters, page and
    query will always have values, so no undefined checking is
    required.
  */

  const { page, query, active } = queryParams;

  return (
    <div>
      <h1>
        You are on page {page} with query {query}
        you are {active ? 'active' : 'inactive'}.
      </h1>
    </div>
  );
}

Query params are strings by default. @42.nl/react-url tries to convert them to more concrete types. It does this based on the default query params you give to useQueryParams. It provides the following transformations:

  1. If the default query param is a boolean it converts to boolean.
  2. If the default query param is a number it converts to number. Also works for fractions such as 3.14.
  3. If the default query param is an array of booleans in converts to an array of booleans.
  4. If the default query param is an array of numbers in converts to an array of numbers.

It does not transform values when:

  1. The default query param is a string.
  2. The default query param is an empty array.

Now that we have seen useQueryParams and urlBuilder it is time to put them together.