#Retaining transformed search params

5 messages · Page 1 of 1 (latest)

unreal pond
#

Hi guys, I've been trying to solve this for hours - how do I transform search params in a way that doesn't break the retainSearchParams middleware?

Use case: supporting multiple formats of the same search param (e.g. for backwards compatibility):

  • /?rootvalue=abc -> should map to rootValue
  • /?rootValue=abc -> should map to rootValue as well
  • If both are present, only the expected one gets used.. you get the idea

Here's a demo: https://stackblitz.com/edit/tanstack-router-retain-nok-21zpypb5?file=src%2Froutes%2F__root.tsx

I thought using zod schema with .transform() would work, and it kinda does, but it completely breaks the retainSearchParams middleware. Is there another way to approach this?

dire minnow
#

Maybe Stupid Idea, but can you throw a redirect to the same route with the updated search params to standardize the output. Aka if you get "rootvalue" -> create new params with name changed to rootValue -> throw a redirect to the same route with updated params

maiden glacier
#

Above is a good idea^

#

I think you can create custom search middleware too

#
search: {
  middlewares: [
    ({ search, next }) => {
      const result = next(search);
      if (typeof result.rootValue !== "undefined" && typeof result.rootvalue !== "undefined") {
        // both defined
        // use one, keep the other
        delete result.rootvalue;
      } else if (typeof result.rootvalue !== "undefined") {
        // rootvalue is defined, but rootValue is not
        // change to rootValue
        result.rootValue = result.rootvalue;
        delete result.rootvalue;
      } // .... continue

      return result;
    }
  ]
}