pbeshai / use-query-params

React Hook for managing state in URL query parameters with easy serialization.
https://pbeshai.github.io/use-query-params
ISC License
2.15k stars 96 forks source link

Add ArrayEnum params and serialiser #218

Closed kuroski closed 2 years ago

kuroski commented 2 years ago

In this PR:


I had the same need for this issue #174, so I've decided to implement a custom version for my application, but I thought of giving it a shot and proposing this change in the package, maybe that would help someone 😉

This is a very raw implementation, but it should work for simple scenarios.

Here is my scenario as an example

type Color = "red" | "green" | "blue";

type FormData = {
  name?: string | null;
  color?: Color[] | null;
};

const Home: NextPageWithAuth = () => {
  const [query, setQuery] = useQueryParams({
    name: StringParam,
    // I know I can use Enums, but I like using union types better, as they don't actually generate code
    color: createEnumArrayParam<Color[]>(["red", "green", "blue"]),
  });

  const { register, handleSubmit, control } = useForm<FormData>({
    defaultValues: query,
  });

  // plain `string` type can't be sent, since I'm relying on prisma, so I need an actual type `Color` coming from query params
  const productQuery = trpc.useQuery(["product.list", { ...query }]);

  // .....
}

closes #174

eranimo commented 2 years ago

This would be great to have!

pbeshai commented 2 years ago

Thanks, this looks good! I think I may make two versions, one that explicitly says it delimits the array to match the other params.