0

I have form in my component, And I want to display default values when form was already filled. I mean when I refresh page I want to display input values from sessionStorage. Main problem is that when i get file type from storage and display it to input file. seems like everything okay. But after submiting form somehow input file reset and type is fileList but lenght 0.So form is already invalid and requires to upload smth(img) again.

Its my useForm in component.

const getInfoFormData = JSON.parse(sessionStorage.getItem('infoFormData'))
const {register, handleSubmit, formState: {errors,touchedFields, isValid}, getValues} = useForm({
        mode: 'all',
        defaultValues: async () => {
            setData({
                ...data,
                firstName: getInfoFormData?.firstName,
                lastName: getInfoFormData?.lastName,
                img: getInfoFormData?.img,
                aboutMe: getInfoFormData?.aboutMe,
                email: getInfoFormData?.email,
                mobile: getInfoFormData?.mobile
            })
            const imgtoLoad = await dataURLtoFile(getInfoFormData.img,'avatar.png')
            return {
                firstName: getInfoFormData?.firstName || '',
                lastName: getInfoFormData?.lastName || '',
                img: imgtoLoad,
                aboutMe: getInfoFormData?.aboutMe || '',
                email: getInfoFormData?.email || '',
                mobile: getInfoFormData?.mobile || ''
            }
        }
    })

its a little code from my inputs. Exactly input file. How can i display input file from storage, cuz i need this input to be required.

<div className='info-img'>
                <label className={errors.img?.message ? 'error' : ' '}>პირადი ფოტოს ატვირთვა</label>
                <label className='input' htmlFor='upload'>ატვირთვა</label>
                <input
                 type='file' 
                 id='upload' 
                 onChange={(event) => getImgValueFromInput(event)} 
                 {...register('img', {required: 'ატვირთეთ ფოტო'})}
                 />
</div>

Killa
  • 1
  • 2

1 Answers1

0

Try setValue inside a useEffect with dependency of typeof window that sets value of the specific field when session storage is available.

Files should first get converted to a data type that can be saved securely like shown in the link below:

https://stackoverflow.com/a/70485949/12098866

Also you could try onInput instead of onChange

zahra shahrouzi
  • 862
  • 7
  • 18
  • As I know i cant setValue for input file, but i will try thx – Killa Feb 10 '23 at 13:37
  • yes, im converting that also, when i refresh page data is also stored, main prolem is that when i submit form only input file resets somehow. and says that need to be required. – Killa Feb 10 '23 at 13:52