UNPKG

1.68 kBJavaScriptView Raw
1"use strict";
2Object.defineProperty(exports, "__esModule", { value: true });
3exports.useUIDSeed = exports.useUID = void 0;
4var React = require("react");
5var react_1 = require("react");
6var context_1 = require("./context");
7var generateUID = function (context) {
8 var quartz = context || context_1.counter;
9 var prefix = (0, context_1.getPrefix)(quartz);
10 var id = (0, context_1.getId)(quartz);
11 var uid = prefix + id;
12 var gen = function (item) { return uid + quartz.uid(item); };
13 return { uid: uid, gen: gen };
14};
15var useUIDState = function () {
16 if (process.env.NODE_ENV !== 'production') {
17 if (!('useContext' in React)) {
18 throw new Error('Hooks API requires React 16.8+');
19 }
20 }
21 var context = (0, react_1.useContext)(context_1.source);
22 var uid = (0, react_1.useState)(function () { return generateUID(context); })[0];
23 return uid;
24};
25/**
26 * returns and unique id. SSR friendly
27 * returns {String}
28 * @see {@link UIDConsumer}
29 * @see https://github.com/thearnica/react-uid#hooks-168
30 * @example
31 * const id = useUID();
32 * id == 1; // for example
33 */
34var useUID = function () {
35 var uid = useUIDState().uid;
36 return uid;
37};
38exports.useUID = useUID;
39/**
40 * returns an uid generator
41 * @see {@link UIDConsumer}
42 * @see https://github.com/thearnica/react-uid#hooks-168
43 * @example
44 * const uid = useUIDSeed();
45 * return (
46 * <>
47 * <label for={seed('email')}>Email: </label>
48 * <input id={seed('email')} name="email" />
49 * {data.map(item => <div key={seed(item)}>...</div>
50 * </>
51 * )
52 */
53var useUIDSeed = function () {
54 var gen = useUIDState().gen;
55 return gen;
56};
57exports.useUIDSeed = useUIDSeed;