SolidJSS
SolidJSโ€ข3y agoโ€ข
3 replies
binajmen

How do you consume server actions response?

It might look as a silly question, but it is unclear for me how you must consume the response (either is it result or error).

export default function Users() {
  const users = useRouteData<typeof routeData>();

  const [creating, { Form }] = createServerAction$(
    async (formData: FormData) => {
      await new Promise((resolve, reject) => setTimeout(resolve, 1000));
      const email = String(formData.get("email"));

      if (email.length < 10) {
        return json({ success: false, fields: { email: "too small" } });    // <-- will end up in result
        // throw json({ success: false, fields: { email: "too small" } });  // <-- will end up in error
      }

      await db.insert(usersTable).values({ email });

      return json({ success: true });
    }
  );

  createEffect(() => console.log("effect:", creating, creating.pending));
  console.log(creating);

  return (
    <div>
      <h1>Users list</h1>
      <ul>
        <For each={users()}>{(user) => <li>{user.email}</li>}</For>
      </ul>
      <Form>
        <label for="email">Email:</label>
        <input type="email" name="email" />
        <Show when={creating.error}>Error: {creating.error/*???*/}</Show>
        <input type="submit" value="submit" />
      </Form>
    </div>
  );
}


If the action failed (form validation, db error, etc.), I'd like to retrieve this info in the response. In the network tab, the result as the type Response (it makes sense). However, how am I suppose to consume the response and extract the JSON I'm sending from the action?
Was this page helpful?