Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 26 additions & 2 deletions components/form.tsx
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
'use client'

import { useState } from 'react'
import { useEffect, useState } from 'react'
import { motion } from 'framer-motion'

import { z } from 'zod'
import { FormDataSchema } from '@/lib/schema'
import { zodResolver } from '@hookform/resolvers/zod'
import { useForm, SubmitHandler } from 'react-hook-form'
import localData from '@/helpers/localData'

type Inputs = z.infer<typeof FormDataSchema>

Expand Down Expand Up @@ -37,9 +38,28 @@ export default function Form() {
trigger,
formState: { errors }
} = useForm<Inputs>({
resolver: zodResolver(FormDataSchema)
resolver: zodResolver(FormDataSchema),
defaultValues: {
firstName: '',
lastName: '',
email: '',
country: '',
street: '',
city: '',
state: '',
zip: ''
}
})

useEffect(() => {
// Load data from localStorage when the component mounts
const savedData = localData({ item: 'formData', type: 'get' })
if (savedData) {
// You might need to set this data to your form using reset or any other way
reset(savedData)
}
}, [])

const processForm: SubmitHandler<Inputs> = data => {
console.log(data)
reset()
Expand All @@ -59,13 +79,17 @@ export default function Form() {
}
setPreviousStep(currentStep)
setCurrentStep(step => step + 1)
// Update local data for the second step if the user goes back to first step
localData({ item: 'formData', type: 'set', data: watch() })
}
}

const prev = () => {
if (currentStep > 0) {
setPreviousStep(currentStep)
setCurrentStep(step => step - 1)
// When the user goes back, update the local data with the current form state
localData({ item: 'formData', type: 'set', data: watch() })
}
}

Expand Down
20 changes: 20 additions & 0 deletions helpers/localData.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
type LocalDataProps = {
item: string;
type: 'set' | 'get';
data?: any;
}

export default function localData({ item, type, data }: LocalDataProps) {
try {
if (type === "get") {
const retrievedData = localStorage.getItem(item);
return retrievedData ? JSON.parse(retrievedData) : null; // Return null if no data
} else if (type === "set" && data !== undefined) { // Check if data is provided when type is set
localStorage.setItem(item, JSON.stringify(data));
return true; // Successfully set data
}
} catch (error) {
console.error("Error handling localStorage data:", error);
return false; // Indicate that an error occurred
}
}
Loading