Skip to content

Fix/fix development error with react strict mode #32

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
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
46 changes: 35 additions & 11 deletions src/index.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { useEffect } from 'react'
import { useCallback, useEffect, useRef, useState } from 'react'
import { SetFieldValue } from 'react-hook-form'

export interface FormPersistConfig {
Expand Down Expand Up @@ -30,27 +30,29 @@ const useFormPersist = (
}: FormPersistConfig
) => {
const watchedValues = watch()
const [localExclude] = useState<string[]>(exclude)
Copy link

@JGJP JGJP Feb 14, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What is the reason for this useState?

By initializing useState with exclude we also lose any reactivity to the value of exclude.


const getStorage = () => storage || window.sessionStorage

const clearStorage = () => getStorage().removeItem(name)
const getStorage = useCallback(() => storage || window.sessionStorage, [storage])
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is the memoization of this function worth the overhead cost of useCallback?

const clearStorage = useCallback(() => getStorage().removeItem(name), [getStorage, name])
const onTimeoutCallback = useCallback(() => onTimeout && onTimeout(), [onTimeout])
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why extract this to another useCallback? Seemed fine as an inline call imo

const _mounted = useRef(true)
Copy link

@JGJP JGJP Feb 14, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I would suggest the value of mounted should be initially false, since we shouldn't consider any component to be mounted until a useEffect runs


useEffect(() => {
const str = getStorage().getItem(name)

if (str) {
if (str && _mounted.current) {
const { _timestamp = null, ...values } = JSON.parse(str)
const dataRestored: { [key: string]: any } = {}
const currTimestamp = Date.now()

if (timeout && (currTimestamp - _timestamp) > timeout) {
onTimeout && onTimeout()
onTimeoutCallback()
clearStorage()
return
}

Object.keys(values).forEach((key) => {
const shouldSet = !exclude.includes(key)
const shouldSet = !localExclude.includes(key)
if (shouldSet) {
dataRestored[key] = values[key]
setValue(key, values[key], {
Expand All @@ -65,18 +67,30 @@ const useFormPersist = (
onDataRestored(dataRestored)
}
}

return () => {
_mounted.current = false
}
}, [
storage,
name,
onDataRestored,
setValue
setValue,
clearStorage,
dirty,
localExclude,
getStorage,
onTimeoutCallback,
timeout,
touch,
validate
])

useEffect(() => {

const values = exclude.length
const values = localExclude.length
? Object.entries(watchedValues)
.filter(([key]) => !exclude.includes(key))
.filter(([key]) => !localExclude.includes(key))
.reduce((obj, [key, val]) => Object.assign(obj, { [key]: val }), {})
: Object.assign({}, watchedValues)

Expand All @@ -86,7 +100,17 @@ const useFormPersist = (
}
getStorage().setItem(name, JSON.stringify(values))
}
}, [watchedValues, timeout])

return () => {
_mounted.current = false
}
Comment on lines +104 to +106
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Does this useEffect need to return this? _mounted.current is not referenced or otherwise modified by this useEffect

}, [
watchedValues,
timeout,
localExclude,
getStorage,
name,
])

return {
clear: () => getStorage().removeItem(name)
Expand Down
40 changes: 36 additions & 4 deletions tests/index.test.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import React from 'react'
import React, { StrictMode } from 'react'
import { vi, describe, test, expect, beforeEach } from 'vitest'
import { render, screen } from '@testing-library/react'
import { useForm } from 'react-hook-form'
import { useForm, UseFormProps } from 'react-hook-form'
import userEvent from '@testing-library/user-event'

import useFormPersist, { FormPersistConfig } from '../src'
Expand All @@ -13,8 +13,8 @@ beforeEach(() => {
})


const Form = ({ onSubmit = () => { }, config = {} }: { onSubmit?: any, config?: Omit<FormPersistConfig, 'watch' | 'setValue'> }) => {
const { register, handleSubmit, watch, setValue } = useForm()
const Form = ({ onSubmit = () => { }, config = {}, useFormConfig = {} }: { onSubmit?: any, config?: Omit<FormPersistConfig, 'watch' | 'setValue'>, useFormConfig?: UseFormProps }) => {
const { register, handleSubmit, watch, setValue } = useForm(useFormConfig)

useFormPersist(STORAGE_KEY, { watch, setValue, ...config })

Expand Down Expand Up @@ -108,4 +108,36 @@ describe('react-hook-form-persist', () => {
expect(JSON.parse(window.sessionStorage.getItem(STORAGE_KEY) || "{}")).toEqual({})
})

test('should apply defaultValues and load persisted changes in React.StrictMode', async() => {
const spy = vi.spyOn(Storage.prototype, 'getItem')

const { unmount, ...rest } = render(
<StrictMode>
<Form useFormConfig={{
defaultValues: {
foo: 'Test'
}
}}
/>
</StrictMode>
)

await userEvent.type(screen.getByLabelText('foo:'), 'foo')
unmount()

render(
<StrictMode>
<Form useFormConfig={{
defaultValues: {
foo: 'Test'
}
}}
/>
</StrictMode>
)

expect(spy).toHaveBeenCalled()
expect(screen.getByLabelText('foo:')).toHaveValue('Testfoo')
})

})