1- import { ref , computed , watch , type Ref , type ComputedRef } from 'vue' ;
1+ import { ref , computed , watch , type Ref , type ComputedRef , watchEffect } from 'vue' ;
22
33export function useControlledState < T , C = T > (
4- value : Ref < T | undefined > ,
5- defaultValue : T ,
4+ value ? : Ref < T | undefined > ,
5+ defaultValue ? : T ,
66 onChange ?: ( v : C , ...args : any [ ] ) => void
7- ) : [ ComputedRef < T > , ( value : T | ( ( prev : T ) => T ) , ...args : any [ ] ) => void ] {
8- const isControlled = computed ( ( ) => value . value !== undefined ) ;
9- const initialValue = value . value ?? defaultValue ;
7+ ) : [ ComputedRef < T | undefined > , ( value : T | ( ( prev : T ) => T ) , ...args : any [ ] ) => void ] {
8+ const isControlled = computed ( ( ) => value ? .value !== undefined ) ;
9+ const initialValue = value ? .value ?? defaultValue ;
1010 const internalState = ref ( initialValue ) as Ref < T > ;
1111 const wasControlled = ref ( isControlled . value ) ;
1212
1313 const currentValue = computed ( ( ) =>
14- isControlled . value ? value . value ! : internalState . value
14+ isControlled . value ? value ? .value : internalState . value
1515 ) ;
1616
17+ watchEffect ( ( ) => {
18+ console . log ( "isControlled" , isControlled . value ) ;
19+ } )
20+
1721 watch ( isControlled , ( newVal , oldVal ) => {
1822 if ( newVal !== oldVal ) {
1923 console . warn (
@@ -24,13 +28,14 @@ export function useControlledState<T, C = T>(
2428 }
2529 } ) ;
2630
31+
2732 function setValue ( newValue : T | ( ( prev : T ) => T ) , ...args : any [ ] ) {
2833 if ( typeof newValue === 'function' ) {
2934 console . warn (
30- 'Function callbacks are not supported. See: https://github.com/adobe/react-spectrum/issues/2320 '
35+ 'Function callbacks are not supported.'
3136 ) ;
3237 const prev = currentValue . value ;
33- const updatedValue = ( newValue as ( prev : T ) => T ) ( prev ) ;
38+ const updatedValue = ( newValue as ( prev ? : T ) => T ) ( prev ) ;
3439
3540 if ( ! isControlled . value ) {
3641 internalState . value = updatedValue ;
@@ -41,7 +46,6 @@ export function useControlledState<T, C = T>(
4146 }
4247 } else {
4348 const shouldUpdate = ! Object . is ( currentValue . value , newValue ) ;
44-
4549 if ( ! isControlled . value ) {
4650 internalState . value = newValue ;
4751 }
0 commit comments