Skip to content
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

fix(utils): atomWithObservable is not resubscribed after remount #1016

Merged
merged 1 commit into from
Mar 3, 2022
Merged
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
5 changes: 4 additions & 1 deletion src/utils/atomWithObservable.ts
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,10 @@ export function atomWithObservable<TData>(
if (!subscription) {
subscription = observable.subscribe(dataListener, errorListener)
}
return () => subscription?.unsubscribe()
return () => {
subscription?.unsubscribe()
subscription = null
}
}
return { dataAtom, observable }
})
Expand Down
45 changes: 43 additions & 2 deletions tests/utils/atomWithObservable.test.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { Suspense } from 'react'
import { fireEvent, render } from '@testing-library/react'
import { ReactElement, Suspense, useState } from 'react'
import { act, fireEvent, render } from '@testing-library/react'
import { Observable, Subject } from 'rxjs'
import { useAtom } from 'jotai'
import { atomWithObservable } from 'jotai/utils'
Expand Down Expand Up @@ -70,3 +70,44 @@ it('writable count state', async () => {
fireEvent.click(getByText('button'))
await findByText('count: 9')
})

it('resubscribe on remount', async () => {
const subject = new Subject<number>()
const observableAtom = atomWithObservable(() => subject)

const Counter = () => {
const [state] = useAtom(observableAtom)

return <>count: {state}</>
}

const Toggle = ({ children }: { children: ReactElement }) => {
const [visible, setVisible] = useState(true)
return (
<>
{visible && children}
<button onClick={() => setVisible(!visible)}>Toggle</button>
</>
)
}

const { findByText, getByText } = render(
<Provider>
<Suspense fallback="loading">
<Toggle>
<Counter />
</Toggle>
</Suspense>
</Provider>
)

await findByText('loading')
act(() => subject.next(1))
await findByText('count: 1')

fireEvent.click(getByText('Toggle'))
fireEvent.click(getByText('Toggle'))

act(() => subject.next(2))
await findByText('count: 2')
})