UNPKG

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