Rocon Website

Location States

HTML's history API (and the history module) supports a data-passing mechanism known as location.state. It allows passing more complex data than a string, including objects and arrays. Its downside is that location.state is not a part of URL. This means that there is no means of direct access to a route with location states; a user must navigate from another route to get to a route with location states.

Location states are defined by State route builders.Rocon.State receives a validator of type (value: unknown) => value is Value where Value is the type of its state.

const toplevelRoutes = Rocon.Path()
  .route("user");

type User = {
  name: string;
  age: number;
}

const userValidator = (value: any): value is User => {
  return (
    value != null &&
    typeof value.name === "string" &&
    typeof value.age === "number"
  );
};

const userRoute = toplevelRoutes._.user
  .attach(Rocon.State("user", userValidator))
  .action(({ user }) => <p>
    Hello, {user.name}!
    You are {user.age} years old.
  </p>);

The validator has two roles: one is to perform a runtime check of whether a value of correct type is passed as a location state, and the other is to tell Rocon the type of the defined state. Thanks to the type of the validator, Rocon can infer the type of user property of the match object. If defining a validator by yourself is cumbersome, a runtime type check library like io-ts can be utilized.

Navigation

Navigation to routes with a location state is just the same as other routes; provide a match object with needed value in it.

navigate(userRoute.route, {
  user: {
    name: "Pikachu",
    age: 24
  }
});