Skip to content

1.0.60 - The normalization update

Compare
Choose a tag to compare
@hazae41 hazae41 released this 06 Sep 22:45
· 789 commits to master since this release

BREAKING CHANGES

  • All type parameters now follow the order D,E,N,K; some types may break if you used type parameters before

CHANGES

  • Added store normalization, out of the box, no dependency needed

Example

We'll use normalization for an array that contains items of type Data, each with an unique id

interface Data {
  id: string
  name: string
}

First, create a schema factory for an item

function getDataSchema(id: string) {
  return XSWR.single<Data>(`/api/data?id=${id}`, fetchAsJson)
}

Then, create a normal for an item

A normal is an object that encapsulates your data, its schema, and a reference to your data (so we can delete the original data and just keep the reference)

function getDataNormal(data: Data) {
  return new XSWR.Normal(data, getDataSchema(data.id), data.id)
}

Then, create a schema for your container, and create a normalizer, it will return then new structure of your container

In this case, all the array is mapped to normals, which will then automatically be replaced by references by XSWR

function getAllDataSchema() {
  function normalizer(data: Data[]) {
    return data.map(getDataNormal)
  }

  return XSWR.single<Data[], Error, string[]>(
    `/api/data/all`,
    fetchAsJson,
    { normalizer })
}

Notice the extra type parameter string[], it's the final type of our container, after normalization

That's it! No dependency needed, it just works!

You can find a full example in test/next/normalizer