Skip to content

Commit a18d398

Browse files
authored
fix: the inView state could be reset with triggerOnce #311 (#312)
1 parent b610f25 commit a18d398

File tree

3 files changed

+14
-2
lines changed

3 files changed

+14
-2
lines changed

src/InView.tsx

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -86,7 +86,9 @@ export class InView extends React.Component<
8686
handleNode = (node?: Element | null) => {
8787
if (this.node) {
8888
unobserve(this.node)
89-
if (!node) this.setState({ inView: false, entry: undefined })
89+
if (!node && !this.props.triggerOnce) {
90+
this.setState({ inView: false, entry: undefined })
91+
}
9092
}
9193
this.node = node ? node : null
9294
this.observeNode()

src/useInView.tsx

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,12 @@ export function useInView(
2323
node => {
2424
if (ref.current) {
2525
unobserve(ref.current)
26-
setState(initialState)
26+
27+
if (!options.triggerOnce) {
28+
// Reset the state, unless the hook is set to only `triggerOnce`
29+
// In that case, resetting the state would trigger another update.
30+
setState(initialState)
31+
}
2732
}
2833
if (node) {
2934
observe(

stories/Hooks.story.tsx

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -129,3 +129,8 @@ storiesOf('useInView hook', module)
129129
</HookComponent>
130130
</ScrollWrapper>
131131
))
132+
.add('Trigger once', () => (
133+
<ScrollWrapper>
134+
<HookComponent options={{ triggerOnce: true }} />
135+
</ScrollWrapper>
136+
))

0 commit comments

Comments
 (0)