Skip to content

Commit

Permalink
feat: add useId
Browse files Browse the repository at this point in the history
  • Loading branch information
wangxingkang committed Jun 21, 2024
1 parent 422381d commit 8131729
Show file tree
Hide file tree
Showing 4 changed files with 42 additions and 1 deletion.
2 changes: 1 addition & 1 deletion packages/core/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,5 +42,5 @@ export * from './useIdle'
export * from './useIsomorphicEffect'
export * from './useEyeDropper'
export * from './useValidatedState'

export * from './useId'
export * from '@rcuse/shared'
21 changes: 21 additions & 0 deletions packages/core/useId/__tests__/index.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import { renderHook } from '@testing-library/react'
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { useId } from '../index'

describe('useId', () => {
beforeEach(() => {
vi.useFakeTimers()
})

it('returns static id', () => {
const view = renderHook(() => useId('test-id'))
expect(view.result.current).toBe('test-id')
})

it('returns random id if static id is not provided', () => {
const view = renderHook(() => useId())
expect(typeof view.result.current).toBe('string')
expect(view.result.current.includes('rcuse')).toBe(true)
expect(view.result.current !== renderHook(() => useId()).result.current).toBe(true)
})
})
17 changes: 17 additions & 0 deletions packages/core/useId/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import { useState } from 'react'
import { useLayoutEffect } from '../helpers/useLayoutEffect'
import { useReactId } from './useReactId'

let count = 0

export function useId(staticId?: string) {
const reactId = useReactId()
const [id, setId] = useState(reactId)

useLayoutEffect(() => {
if (!staticId)
setId((reactId: string) => reactId ?? String(count++))
}, [])

return staticId || (id ? `rcuse-${id}` : '')
}
3 changes: 3 additions & 0 deletions packages/core/useId/useReactId.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
import React from 'react'

export const useReactId = (React as any)['useId'.toString()] || (() => undefined)

0 comments on commit 8131729

Please sign in to comment.