Skip to content

Commit bdb2e86

Browse files
committed
Load target groups and e-mail address from URL
1 parent 55ad6cc commit bdb2e86

1 file changed

Lines changed: 26 additions & 4 deletions

File tree

app/(standalone)/subscribe/SubscribePage.tsx

Lines changed: 26 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
"use client";
22

33
import { useState } from "react";
4+
import { useRouter, useSearchParams } from "next/navigation";
45

56
import { RequiredFieldMarker } from "~/components/form/RequiredFieldMarker";
67
import { looksLikeEmailAdress } from "~/src/utils";
@@ -40,9 +41,24 @@ export const SubscribePage = () => {
4041
},
4142
];
4243

44+
const router = useRouter();
45+
const searchParams = useSearchParams() ?? [];
46+
const [formState, setFormState] = useState<FormState>({
47+
...initialFormState,
48+
selectedTargetGroups: decodeTargetGroupIds(searchParams),
49+
email: searchParams.get("email") ?? "",
50+
});
51+
4352
return (
4453
<Form
4554
options={targetGroups}
55+
state={formState}
56+
setState={(state) => {
57+
router.replace(
58+
"/subscribe/?" + encodeTargetGroupIds(state.selectedTargetGroups),
59+
);
60+
setFormState(state);
61+
}}
4662
onSubmit={async (state) => {
4763
// TBD: Handle errors and success
4864
await fetch("/subscribe/submit", {
@@ -69,12 +85,18 @@ type FormState = {
6985

7086
const initialFormState: FormState = {
7187
submitting: false,
72-
selectedTargetGroups: ["cist.digital"],
88+
selectedTargetGroups: [],
7389
firstName: "",
7490
lastName: "",
7591
email: "",
7692
};
7793

94+
const encodeTargetGroupIds = (list: TargetGroupId[]) =>
95+
new URLSearchParams(list.map((val) => ["g", val]));
96+
97+
const decodeTargetGroupIds = (params: URLSearchParams) =>
98+
params.getAll("g") as TargetGroupId[];
99+
78100
const canSubmit = (state: FormState) =>
79101
state.firstName !== "" &&
80102
state.lastName !== "" &&
@@ -84,12 +106,12 @@ const canSubmit = (state: FormState) =>
84106

85107
type FormProps = {
86108
options: TargetGroup[];
109+
state: FormState;
110+
setState: (state: FormState) => void;
87111
onSubmit: (state: FormState) => Promise<void>;
88112
};
89113

90-
const Form = ({ options, onSubmit }: FormProps) => {
91-
const [state, setState] = useState<FormState>(initialFormState);
92-
114+
const Form = ({ options, state, setState, onSubmit }: FormProps) => {
93115
const toggleTargetGroup = (id: TargetGroupId) => {
94116
const oldValue = state.selectedTargetGroups;
95117
const selectedTargetGroups = oldValue.includes(id)

0 commit comments

Comments
 (0)