Skip to content

Commit

Permalink
✨ feat: Implemented hook to control form
Browse files Browse the repository at this point in the history
  • Loading branch information
caioaletroca committed Dec 18, 2024
1 parent 73b897d commit c859d4e
Show file tree
Hide file tree
Showing 2 changed files with 92 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
import { renderHook, act } from '@testing-library/react'
import { useTransactionFormControl } from './use-transaction-form-control'
import { TransactionFormSchema } from './schemas'

describe('useTransactionFormControl', () => {
const initialValues: TransactionFormSchema = {
asset: '',
value: 0,
source: [],
destination: []
} as any

it('should initialize with step 0', () => {
const { result } = renderHook(() =>
useTransactionFormControl(initialValues)
)
expect(result.current.step).toBe(0)
})

it('should set step to 1 when value, asset, source, and destination are provided', () => {
const values: TransactionFormSchema = {
asset: 'BTC',
value: 100,
source: [{ account: 'source1' }],
destination: [{ account: 'destination1' }]
} as any

const { result } = renderHook(() => useTransactionFormControl(values))

act(() => {
result.current.step
})

expect(result.current.step).toBe(1)
})

it('should set step to 0 when any of value, asset, source, or destination are missing', () => {
const values: TransactionFormSchema = {
asset: '',
value: 100,
source: [{ account: 'source1' }],
destination: [{ account: 'destination1' }]
} as any

const { result } = renderHook(() => useTransactionFormControl(values))

act(() => {
result.current.step
})

expect(result.current.step).toBe(0)
})

it('should not change step if step is 2 or more', () => {
const values: TransactionFormSchema = {
asset: 'BTC',
value: 100,
source: [{ account: 'source1' }],
destination: [{ account: 'destination1' }]
} as any

const { result } = renderHook(() => useTransactionFormControl(values))

act(() => {
result.current.setStep(2)
})

expect(result.current.step).toBe(2)
})
})
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import { useEffect } from 'react'
import { useStepper } from '@/hooks/use-stepper'
import { TransactionFormSchema } from './schemas'

export const useTransactionFormControl = (values: TransactionFormSchema) => {
const { step, setStep, ...props } = useStepper({ maxSteps: 3 })
const { asset, value, source, destination } = values

useEffect(() => {
if (step < 2) {
// If the user has filled the required fields, move to the next step
if (value && asset && source?.length > 0 && destination?.length > 0) {
setStep(1)
// Reset back to initial step if the user has removed the required fields
} else {
setStep(0)
}
}
}, [value, asset, source, destination])

return { step, setStep, ...props }
}

0 comments on commit c859d4e

Please sign in to comment.