npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

refinerdb-react

v2.0.2

Published

## Install

Downloads

7

Readme

RefinerDB - React

Install

npm install refinerdb-react

Quick start

  1. Define your getData async function
  2. Define your indexes
  3. Wrap your app in a RefinerDBProvider
  4. Create a results view component
  5. Create a refiner panel

Refiners

! IMPORTANT ! - To use these hooks you need to wrap your components in a RefinerDBProvider component.

Text Refiner

  • Useful for textbox refiner controls
  • Performs a "contains" query
// Setup a refiner on the 'title' index
let [value, setValue] = useTextRefiner("title")
// Use it in JSX
<input value={value} onChange={(e) => setValue(e.currentTarget.value)}>

Multiselect Refiner

  • Useful for OR queries
  • Ex: Filter movies by genre "Action" or "Comedy"
  • Uses a string[]
  • Returns a tuple: [values, setValues, options, events ]
    • values is the string[] of active filter values
    • setValues is the setter for the string[] of filter values
    • options is the list of available RefinerOption
      • In the shape of { key, count}
      • E.g. { key: "Drama", count: 42 }
    • events Is a bonus that provider dom event handlers for working with common UI scenarios
      • selectOnChange can be applied to the onChange of a <select>
        • <select value={values} onChange={events.selectOnChange}>
      • checkboxOnChange can be applied to the onChange of an <input type='checkbox'>

Don't forget, because it is a tuple you can rename any of these destructured items

let [values, setValues, options, { selectOnChange, checkboxOnChange }] = useMultiselectRefiner(
  indexKey,
  (debounce = 0)
);

Here is an example "CheckboxRefiner" component

function CheckboxRefiner({ indexKey, label = "" }: Props) {
  let [values = [], , options = [], events] = useMultiselectRefiner(indexKey);

  return (
    <Fieldset label={label || indexKey}>
      {options.map((option) => (
        <div key={option.key}>
          <label>
            <input
              type="checkbox"
              value={option.key}
              checked={values.includes(option.key)}
              onChange={events.checkboxOnChange}
            />
            {option.key} - {option.count}
          </label>
        </div>
      ))}
    </Fieldset>
  );
}

Date Range Refiner

  • Provides { min, max, setMin, setMax }
  • The min and max are formatted date strings, YYYY-MM-dd, so you can easily pop them on a <input type='date' />
function CreatedDateRefiner() {
  // Reference the 'created_at' index
  let range = useDateRangeRefiner("created_at");
  // range is { min, max, setMin, setMax }
  return (
    <Fieldset label={label || indexKey}>
      <div className="">
        <input
          placeholder="Min"
          value={range.min}
          onChange={(e) => range.setMin(e.currentTarget.valueAsDate)}
          type="date"
        />
        <div>to</div>
        <input
          placeholder="Max"
          value={range.max}
          onChange={(e) => range.setMax(e.currentTarget.valueAsDate)}
          type="date"
        />
      </div>
    </Fieldset>
  );
}

Number Range Refiner

  • Provides { min, max, setMin, setMax }
function RatingRefiner() {
  // Reference the 'rating' index which is IndexType.Number
  let range = useNumberRangeRefiner("rating");

  return (
    <label>
      Rating
      <br />
      <input
        placeholder="Min"
        value={range.min + ""}
        onChange={(e) => range.setMin(e.target.value)}
        type="number"
      />
      <input placeholder="Max" value={range.max + ""} onChange={(e) => range.setMax(e.target.value)} type="number" />
    </label>
  );
}

Generic useRefiner

useRefiner(indexKey)

You pass in the index key and this hook will provide the filter value, and setValue method for changing the filter value, and the refiner options.

For multi-select

// A mutli-value string refiner, with the refiner options
let { value, setValue, options } = useRefiner<string[]>("genre");

For Dates and Numbers it is common to use a MinMaxFilterValue refiner. This will re

// A { min, max } refiner
let { value, setValue } = useRefiner<MinMaxFilterValue>("score");

You can also pass an optional RefinerConfig as a second param to the hook.

In this example we disable the debounce.

let { value = "", setValue, options = [] } = useRefiner<string>(indexKey, { debounce: 0 });

Results

useQueryResult

Keeps you up to date with the latest QueryResult. As soon as a query completes (after a filter change or a reindex), the useQueryResult state will update and you will re-render.

let { items, totalCount } = useQueryResult();

Example component that takes a renderItem prop to call for each result item

function ItemResults({ renderItem }) {
  let result = useQueryResult();
  if (!result || !result.items) return null;
  if (!result.items.length) return <>No Results</>;
  return <div>{result.items.map(renderItem)}</div>;
}
export interface QueryResult {
  key: string;
  items: any[];
  refiners: {
    [key: string]: RefinerOption[];
  };
  totalCount: number;
}

Sorting

useSort

type Sort = {
  sortKey: string;
  sortDir: "asc" | "desc";
  setSortKey: (indexKey: string) => void;
  setSortDir: (dir: "asc" | "desc") => void;
  toggleDir: () => void;
  /** Each registered index can be sorted */
  options: {
    /** index key */
    value: string;
    /** Uses the index label */
    text: string;
  };
};
export default function SortControl() {
  let sort = useSort();
  return (
    <div className="rdb-sort" style={{ display: "flex" }}>
      <select value={sort.sortKey} onChange={(e) => sort.setSortKey(e.currentTarget.value)}>
        {sort.options.map((o) => (
          <option key={o.value} value={o.value}>
            {o.text}
          </option>
        ))}
      </select>
      <button
        style={{ marginLeft: "5px" }}
        className="button-outline"
        title="Toggle sort direction"
        onClick={(e) => sort.toggleDir()}
      >
        {sort.sortDir}
      </button>
    </div>
  );
}

Lower Level

useIndexStatus

Gives you the current IndexState (idle, stale, pending, etc...) of your database.

useIndexStatus((status) => {
  if (status === "idle") {
    // do work
  }
});

useCriteria

Your RefinerDB instance keeps track of things like the filtering, sorting and paging in the criteria.

Using this hook will give your back the QueryCriteria value on your RefinerDB instance, as well as an updateCriteria function that takes an updates object and merges in your changes (vs completely replacing the criteria).

let [criteria, updateCriteria] = useCriteria();
export interface QueryCriteria {
  filter?: Filter;
  sort?: string;
  sortDir?: "asc" | "desc";
  limit?: number;
  skip?: number;
}

useIndexes

let [indexes, setIndexes] = useIndexes();

useRefinerDB

You maybe don't need this one for most situations, but it is an escape hatch if you want to get at the actual RefinerDB instance. Most other hooks are built on top of this one.

let refinerDB = useRefinerDB();

Tutorial

First, consider your data.

  • Which properties do you want to refine by?
  • What kind of refiner control would each have?
    • Multi value checkbox?
    • Dropdown?
    • Number Range (min and max values)?
    • Textbox w/ a "contains" search?
    • etc...

Pretend we are dealing an array of Movie objects:

{
  title: "A Star Is Born",
  id: 332562,
  released: "2018-10-03",
  score: 7.5,
  genres: ["Drama", "Music", "Romance"],
}

We might want...

  • A textbox refiner that does a contains filter on title
  • A date range refiner that filters the released date by a min and/or a max
  • A multiselect refiner that filters the genre
  • A number range refiner that filters by the score by a min and/or a max

TODO: Finish tutorial