Skip to content

Fresh 2: Pattern using forms #3059

@Frixxie

Description

@Frixxie

Hey first of great framework, it is a pleasure to use.
I was wondering on a pattern using forms with props passed to the component

I have something looking like:

interface NewMeasurementProps {
  device_id: number;
  sensor_id: number;
  value: number;
  devices: Device[];
  sensors: Sensor[];
}

export const handler = {
  async GET(ctx: FreshContext<NewMeasurementProps>) {
    const device_id = ctx.url.searchParams.get("device_id") || "";
    const sensor_id = ctx.url.searchParams.get("sensor_id") || "";
    const value = ctx.url.searchParams.get("value") || "";

    if (device_id && sensor_id && value) {
      await createMeasurement(
        parseInt(device_id),
        parseInt(sensor_id),
        parseFloat(value),
      );
      console.log(
        "Measurement created:",
        `Device ID: ${device_id}, Sensor ID: ${sensor_id}, Value: ${value}`,
      );
      return Response.redirect(`${ctx.url.origin}/measurements`);
    }

    const devices = await getDevices();
    const sensors = await getSensors();

    ctx.state.devices = devices;
    ctx.state.sensors = sensors;

    return new_measurement(ctx);
  },
};

export default function new_measurement(ctx: FreshContext<NewMeasurementProps>) {
// return form mark up ...
// <form>
// </form>
}

Intuitively i feel like this handler tries to do two things:

  • Handle creating the new measurement which came from the form
  • Fetch the options which will be presented to the client

Are there any way to do this in a cleaner way?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions