1.4.1 • Published 1 month ago

next-query-utils v1.4.1

Weekly downloads
-
License
MIT
Repository
github
Last release
1 month ago

Next Query Utils

npm version License: MIT

This library provides utility functions to deal with Parsed Query Objects (especially of Next.js)

このライブラリには、Parsed Query Object (特に Next.js のもの)を取り扱うためのユーティリティ関数群が含まれます。

Links リンク集

Install

// with npm
npm i next-query-utils

// with yarn
yarn add next-query-utils

Usages 使い方

Getting single value 単独の値を取得する

?id=aaa or ?id=aaa&id=other -> "aaa"

// before
const _id = router.query["id"]
const id = Array.isArray(id) ? id[0] : id

// after
const id = getSingleQueryParam(router.query, "id")

Removing some params 値を取り除く

?start_on=2022-03-02&item_type=stationary&item_type=book -> ?start_on=2022-03-02&item_type=stationary

Before

// before
const removeQuery = (
  query: ParsedUrlQuery, 
  key: string,
  pred: string
) => {
  const value = query[key]

  // if empty, leave query as it is.
  if (!value) return query;
  if (Array.isArray(value)) {
    if(value.length === 0) return query;

    // if non-empty array of string
    return { ...acc, [key]: value.filter(s => s !== pred) };
  }

  // if single string (not empty)
  return { ...acc, [key]: (s !== value) ? value : [] };
}

After

// after
router.push(
  removeQueryParam({ 
    item_type: "book"
  })(router.query)
)

Keeping some params (or Next.js's dynamic routes) from being reset (Next.js's の動的ルートや)パラメータを残して他を削除する

/[postId]?other=value&other2=value -> /[postId]


In pages with Next.js's dynamic routes, router.query include them (in this example, .postId). so they MUST be kept from resetting.

In this case, use resetQuery() with ignore option.


Next.js の動的ルートがあるページでは、それが router.query に含まれる。(この例では .postId) なので、それらは 削除してはいけない

このようなケースでは resetQuery()ignore オプションを使いましょう。


// before
router.push({ postId: router.query["postId"] })

// after
router.push(resetQuery({ ignore: "postId" })(router.query))

Checking if query is empty ignoring some params (e.g. dynamic routes) (動的ルートのような)パラメータ幾つかを無視して、クエリが空であるか確かめる

  • True if /items/[postId]
  • False if /items/[postId]?param1=aa

Likewise, you need to ignore dynamic routes in order to check if the query is empty.

In this case, use isQueryEmpty() with ignore option.


前の例と同じように、クエリが空であるか確かめるためには、 動的ルート を無視する必要があります。

このようなケースでは、isQueryEmpty()ignore オプションを使いましょう。


isQueryEmpty(router.query, { ignore: "postId" })

License

This library is licensed under the terms of MIT License

1.4.1

1 month ago

1.4.0

2 months ago

1.3.0

4 months ago

1.2.0

4 months ago

1.2.1

4 months ago

1.1.0

10 months ago

1.0.0

2 years ago

1.0.0-alpha.0

2 years ago

0.2.4

2 years ago

0.2.3

2 years ago

0.2.2

2 years ago

0.2.1

2 years ago

0.2.0

2 years ago

0.1.0

2 years ago

0.0.1

2 years ago

0.0.0

2 years ago