({
sourceId,
sourceValue,
}: {
sourceId: string;
sourceValue: T;
})
| 34 | * ``` |
| 35 | */ |
| 36 | export const useDraftField = <T>({ |
| 37 | sourceId, |
| 38 | sourceValue, |
| 39 | }: { |
| 40 | sourceId: string; |
| 41 | sourceValue: T; |
| 42 | }) => { |
| 43 | const [state, setState] = useState<DraftFieldState<T> | null>(null); |
| 44 | |
| 45 | const isCurrent = |
| 46 | state?.sourceId === sourceId && Object.is(state.sourceValue, sourceValue); |
| 47 | const value = isCurrent ? state.value : sourceValue; |
| 48 | const error = isCurrent ? state.error : null; |
| 49 | |
| 50 | const setValue = (nextValue: T) => { |
| 51 | setState((current) => { |
| 52 | const keepError = |
| 53 | current?.sourceId === sourceId && |
| 54 | Object.is(current.sourceValue, sourceValue); |
| 55 | |
| 56 | return { |
| 57 | sourceId, |
| 58 | sourceValue, |
| 59 | value: nextValue, |
| 60 | error: keepError ? current.error : null, |
| 61 | }; |
| 62 | }); |
| 63 | }; |
| 64 | |
| 65 | const setError = (nextError: string | null) => { |
| 66 | setState((current) => { |
| 67 | const currentValue = |
| 68 | current?.sourceId === sourceId && |
| 69 | Object.is(current.sourceValue, sourceValue) |
| 70 | ? current.value |
| 71 | : sourceValue; |
| 72 | |
| 73 | return { |
| 74 | sourceId, |
| 75 | sourceValue, |
| 76 | value: currentValue, |
| 77 | error: nextError, |
| 78 | }; |
| 79 | }); |
| 80 | }; |
| 81 | |
| 82 | return { value, setValue, error, setError }; |
| 83 | }; |
no test coverage detected