Fun with Remix (React) and the Discogs API

Fun with Remix (React) and the Discogs API

I’d wish to share and hopefully encourage a few of you to do extra facet initiatives.

This is how I thought of constructing a vinyl checklist internet app, the method of constructing it, together with "some" not all technical particulars.

First some context.

I had a "want" and an itch to get some recreation time with Remix.

Best solution to study is to construct one thing, ideally one thing with/round one thing that you’re care about.

It isn’t any secret that I’m an enormous fan of music. I’ve been gathering and enjoying records over time, on and off… and proper now very a lot on.

I discovered a neighborhood report retailer that I like Filter Musikk, I’ve been shopping for records from them for the final couple of minutes now.

They have a Discogs retailer on-line. Discogs is market for music, it is like eBay for music, however higher.

Anyways, lets speak about code the Discogs API and the way I’ve been enjoying round with it.

I believed it could be cool to construct slightly app that may permit me to see what they’ve in inventory.

🎹 Live demo right here

The knowledge

I like to avoid wasting my endpoints in collections in Postman, so I can simply consult with them later.

Here is the Discogs API endpoint I used to get the stock of a person.

https://api.discogs.com/customers/username/stock
?standing=standing
&kind=kind
&sort_order=sort_order
&per_page=per_page
&web page=web page

Fairly easy.

Discogs API collection

The plan and design

Keep it clear easy design. Focus on the music, the records and the paintings.

Discogs App design

The stack

Remix for the server facet rendering. I used to be solely involved with studying how issues work in Remix with loaders, routes and actions. So I didn’t construct something
from scratch.

I used Tailwind CSS for the styling as a result of it is quick and simple to make use of, after a second thought I made a decision to make use of shadcn/ui
so I didn’t must construct the parts from scratch.

The code

Make use of the Remix sources for constructing the app, no sense reinveinting the wheel.

I used the server facet pagination by Jacob Paris.

Type definitions

I wish to get occustomed to the information I’m working with, so I outline the categories I will probably be working with.

export interface Pagination {
  objects: quantity;
  web page: quantity;
  pages: quantity;
  per_page: quantity;
  urls: Record<
    string,
    {
      final: string;
      subsequent: string;
    }
  >;
}

export interface Price {
  forex: string;
  worth: quantity;
}

interface UniquePrice {
  curr_abbr: string;
  curr_id: quantity;
  formatted: string;
  worth: quantity;
}

interface SellerStats {
  score: string;
  stars: quantity;
  complete: quantity;
}

interface Seller {
  id: quantity;
  username: string;
  avatar_url: string;
  stats: SellerStats;
  min_order_total: quantity;
  html_url: string;
  uid: quantity;
  url: string;
  fee: string;
  delivery: string;
  resource_url: string;
}

interface Image {
  kind: string;
  uri: string;
  resource_url: string;
  uri150: string;
  width: quantity;
  peak: quantity;
}

interface ReleaseStatsCommunity {
  in_wantlist: quantity;
  in_collection: quantity;
}

interface ReleaseStats {
  group: ReleaseStatsCommunity;
}

interface Release {
  thumbnail: string;
  description: string;
  photos: Image[];
  artist: string;
  format: string;
  resource_url: string;
  title: string;
  yr: quantity;
  id: quantity;
  label: string;
  catalog_number: string;
  stats: ReleaseStats;
}

export interface Listing {
  id: quantity;
  resource_url: string;
  uri: string;
  standing: string;
  situation: string;
  sleeve_condition: string;
  feedback: string;
  ships_from: string;
  posted: string;
  allow_offers: boolean;
  offer_submitted: boolean;
  audio: boolean;
  worth: Price;
  original_price: UniquePrice;
  shipping_price: Record<string, unknown>;
  original_shipping_price: Record<string, unknown>;
  vendor: Seller;
  launch: Release;
}

export interface InventoryFetchResponse {
  pagination: Pagination;
  listings: Listing[];
}

Inventory server element

import kind { LoaderFunction, MetaFunction } from "@remix-run/node";
import { json, useLoaderData } from "@remix-run/react";
import { Footer } from "~/parts/footer";
import { PaginationBar } from "~/parts/paginationBar";
import { StatusAlert } from "~/parts/StatusAlert";
import { fetchUserInventory } from "~/stock";
import { Inventory } from "~/stock/stock";

export const loader: LoaderFunction = async ({ request }) => {
  const url = new URL(request.url);
  const searchParams = new URLSearchParams(url.search);
  const pageNumber = searchParams.get("web page") || "1";

  attempt {
    const knowledge = await fetchUserInventory(
      pageNumber,
      "12",
      course of.env.SELLER_USERNAME,
      "on the market",
      "listed",
      "desc",
    );

    return json({ stock: knowledge, ENV: { sellerUsername: course of.env.SELLER_USERNAME } });
  } catch (error) {
    console.log("Error fetching stock:", error);
    return json({ error: "Failed to load stock. Please attempt once more later or" }, { standing: 500 });
  }
};

export const Meta: MetaFunction = () => {
  const { ENV } = useLoaderData<typeof loader>();
  return [
    {
      title: `Shop ${ENV.sellerUsername} records`,
    },
    {
      name: "description",
      content: `Buy some vinyl records from ${ENV.sellerUsername}`,
    },
  ];
};

export default perform Index() {
  const { stock, error } = useLoaderData<typeof loader>();

  if (error) {
    <StatusAlert {...error} />;
  }

  if (!stock || !stock.pagination) {
    return <div>No stock knowledge out there.</div>;
  }

  return (
    <>
      <Inventory {...stock} />
      <PaginationBar complete={stock.pagination.pages} />
      <Footer />
    </>
  );
}

The Inventory element takes the stock knowledge and renders it, it’s the entry level for the app index web page, no routes deliberate.

I present an alert if there may be an error fetching the information, with a hyperlink to Discogs api standing web page.

Remix works like this:

  • you might have a loader perform that fetches the information server facet and returns it to the element wrapped by json() perform
  • the default Index perform then renders the information
  • meta perform is used to set the title and outline of the web page.

fetchUserInventory perform

export const loader: LoaderFunction = async ({ request }) => {
  const url = new URL(request.url);
  const searchParams = new URLSearchParams(url.search);
  const pageNumber = searchParams.get("web page") || "1";

  attempt {
    const knowledge = await fetchUserInventory(
      pageNumber,
      "12",
      course of.env.SELLER_USERNAME,
      "on the market",
      "listed",
      "desc",
    );

    return json({ stock: knowledge, ENV: { sellerUsername: course of.env.SELLER_USERNAME } });
  } catch (error) {
    console.log("Error fetching stock:", error);
    return json({ error: "Failed to load stock. Please attempt once more later or" }, { standing: 500 });
  }
};
  • this perform is used to fetch the information from the Discogs API,
  • it takes the web page quantity, variety of objects per web page, vendor username, standing, situation, kind order as arguments.
  • it returns the information and the vendor username to the loader perform.
  • returns an error if there may be an error fetching the information.

Inventory consumer element

The card element is your typical React card element, it has a header, content material and footer.

I construct string of the artist and music title and cross it to the hyperlink, which when clicked launches YouTube Music, its not good. Some occasions it doesn’t discover the music, nevertheless it works more often than not.

import React from "react";
import {
  Card,
  CardContent material,
  CardDescription,
  CardFooter,
  CardHeader,
  CardTitle,
} from "~/parts/ui/card";
import { cn } from "~/lib/utils";
import kind { InventoryFetchResponse, Listing } from "./stock.sorts";

export const Inventory = (knowledge: InventoryFetchResponse): React.ReactFactor => {
  return (
    <part className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 2xl:grid-cols-6 gap-4 justify-items-start pb-7">
      {knowledge.listings.map((itemizing: Listing) => (
        <article
          id={itemizing.launch.title}
          key={itemizing.launch.title}
          className="flex justify-start w-full"
        >
          <Card className={cn("p-0 shadow-none w-full overflow-hidden")}>
            <div className="justify-items-start">
              <CardHeader
                className="flex-1 h-40 sm:h-60 md:h-90 lg:h-100 p-0 relative"
                title={itemizing.launch.title}
                model={{
                  backgroundImage: itemizing.launch.photos[0]
                    ? `url(${itemizing.launch.photos[0].uri})`
                    : "",
                  backgroundSize: "cowl",
                  backgroundPosition: "heart",
                }}
              >
                {itemizing.situation ?? itemizing.situation}
              </CardHeader>
              <CardContent material className="flex-1 pt-4">
                <CardTitle className="text-sm">
                  {itemizing.launch.title}
                </CardTitle>
                <CardDescription className="leading-6 text-black">
                  <robust>Artist:</robust> {itemizing.launch.artist}
                  <br />
                  <robust>Label:</robust> {itemizing.launch.label} -{" "}
                  {itemizing.launch.catalog_number}
                  <br />
                  <robust>Released:</robust> {itemizing.launch.yr}
                  <br />
                  <robust>Price:</robust> {itemizing.original_price.formatted}
                </CardDescription>
                <CardDescription className="leading-6">
                  <span className="grid grid-cols-1 md:grid-cols-2 gap-1">
                    <a
                      href={itemizing.uri}
                      goal="_blank"
                      rel="noopener noreferrer"
                      className="text-xs text-white border-0 border-black-600 bg-black hover:text-color-black rounded-md p-2 mt-2 "
                    >
                      View on Discogs
                    </a>
                    <a
                      href={`https://music.youtube.com/search?q=${
                        encodeURIComponent(
                          itemizing.launch.title,
                        )
                      } ${encodeURIComponent(itemizing.launch.artist)}`}
                      goal="_blank"
                      rel="noopener noreferrer"
                      className="flex justify-start text-xs text-white border-0 border-black-600 bg-black hover:text-color-black rounded-md p-2 mt-2"
                    >
                      <span className="w-[24px] mt-[2px]">
                        <img
                          src={"./icon-youtube.svg"}
                          alt="YouTube"
                          width={16}
                          peak={16}
                        />
                      </span>
                      <span>Listen</span>
                    </a>
                  </span>
                </CardDescription>
              </CardContent material>
            </div>
            <CardFooter className="p-0"></CardFooter>
          </Card>
        </article>
      ))}
    </part>
  );
};

The consequence

Live demo right here

Discogs App result

Conclusion

I benefit from the plug and play nature of Remix, the documentation is sweet and simple to comply with, it is easy to get began and construct one thing shortly. I just like the server facet rendering and the best way it handles knowledge fetching with the loader and hooks to get the information out its concise, didn’t get the possibility but to make use of an motion as I might want to construct kind (arising subsequent a web site search).

Remix concentrate on efficiency and Web requirements, which is an effective factor. Did not attain for Axios or something like that as a result of I didn’t have to, the fetch API is sweet sufficient for doing easy server facet fetches if no cacheing is required. When it Remix merges into React Router 7 I’ll proceed to make use of it.

Ask me once more sooner or later when React 19 is out.

Get the code on GitHub.

Vinyl

by way of DEV Community: react https://dev.to/t/react

September 23, 2024 at 10:04PM