behnam rahmani
behnam rahmani

Reputation: 71

How to return 404 in Qwik onGet?

I'm using Qwik, and I want to return 404 when from my onGet method.

Unfortunately the docs does not include an example regarding this. And I can't find anything through Google search.

Basically I want to do this:

const onGet = async({ params, url }) => {
    // searching the DB or API for the item
    // return the item if it exist,
    // but return 404 it it does not
    // and I don't know how to return 404
}

Upvotes: 2

Views: 388

Answers (2)

Harsh Mangalam
Harsh Mangalam

Reputation: 1299

Using qwikcity loader$

import { component$ } from "@builder.io/qwik";
import { loader$ } from "@builder.io/qwik-city";

export const githubLoader = loader$(async ({ fail }) => {
  try {
    const res = await fetch("https://api.github.com/users/harshmangalam");
    if (res.ok) {
      const user = await res.json();
      return user;
    }

    // return error status for 401,403,404 ,500 etc...
    return fail(res.status, {
      message: "Error message",
    });
  } catch (error) {
    return fail(500, {
      message: "error message",
    });
  }
});

export default component$(() => {
  const githubSignal = githubLoader.use();

  return <pre>{JSON.stringify(githubSignal.value, null, 4)}</pre>;
});

Add some non-exists username you will get error message.

Upvotes: 1

Harsh Mangalam
Harsh Mangalam

Reputation: 1299

import { component$, Resource } from "@builder.io/qwik";
import {
  type RequestHandler,
  useEndpoint,
  type DocumentHead,
} from "@builder.io/qwik-city";

export const onGet: RequestHandler = async ({ response }) => {
  const res = await fetch("https://api.github.com/users/harshmangalam");
  if (res.ok) {
    const user = await res.json();
    return user;
  }

  // return error status for 401,403,404 ,500 etc...
  throw response.error(res.status);
};

export default component$(() => {
  const resource = useEndpoint<typeof onGet>();

  return (
    <Resource
      value={resource}
      onResolved={(data) => <pre>{JSON.stringify(data, null, 4)}</pre>}
      onRejected={(error) => <pre>{JSON.stringify(error, null, 4)}</pre>}
      onPending={() => <p>Loading...</p>}
    />
  );
});

Upvotes: 0

Related Questions