-1

This is a remix project using Printful and Cloudinary API. I am having trouble figuring out how to get both objects to return correctly. In the loader function, I am returning a JSON for product info and a list of categories to place the product into.

If return the product.result like this, return json(product.result); then the product renders as intended. If I include categories like this, return json([product.result, categories]); then product returns undefined. Here is my loader function.

export const loader: LoaderFunction = async ({ request }) => {
  try {
    const url = new URL(request.url);
    const id = url.searchParams.get("id");
    console.log("Product ID:", id);
    const categories = await getCategories();
    if (id === null) {
      return json(
        { error: "Missing id parameter", categories },
        { status: 400 }
      );
    } else {
      const product = await getPrintfulProduct({ id });
      console.log("Fetched Product Data:", product);
      if (product.error) {
        if (product.error.reason === "NotFound") {
          return json(
            { error: "Product not found", categories },
            { status: 404 }
          );
        }
        return json({ error: product.error, categories }, { status: 500 });
      }
      return json([product.result, categories]);
    }
  } catch (error) {
    console.error("Loader Error:", error);
    return json({ error: "Internal Server Error" }, { status: 500 });
  }
};

I can share the whole code if you think it's not the loader function or if it helps.

1 Answer 1

0

I recommend doing something like this:

return json({ product: product.result, categories })

This will return an object like:

{
  "product": { ... },
  "categories": [ ... ],
}

Then in your component, you can do:

const { product, categories } = useLoaderData<typeof loader>()
Sign up to request clarification or add additional context in comments.

1 Comment

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.