Skip to content

Commit 2033090

Browse files
scroll to last y value on page reload
1 parent ab3623d commit 2033090

File tree

4 files changed

+36
-0
lines changed

4 files changed

+36
-0
lines changed

src/app/page.tsx

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,9 +4,11 @@ import Feed from '@/components/feed/Feed'
44
import Footer from '@/components/footer/Footer'
55
import Navigation from '@/components/navigation/Navigation'
66
import { useFocusTrap } from '@/hooks/useFocusTrap'
7+
import { useSetWindowScrollY } from '@/hooks/useSetWindowScrollY'
78

89
export default function Home() {
910
useFocusTrap()
11+
useSetWindowScrollY()
1012

1113
return (
1214
<div className="min-h-svh flex flex-col items-center justify-start bg-gradient-to-b from-stone-700 to-stone-800">

src/components/feed/Feed.tsx

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ import {
1414
import fetchFeedItems from '@/api/fetchFeedItems'
1515
import { FeedItemsType } from '@/types/types'
1616
import { getItemFromSessionStorage } from '@/utils/getItemFromSessionStorage'
17+
import { getWindowScrollY } from '@/utils/getWindowScrollY'
1718

1819
const Feed = () => {
1920
const PAGE_SIZE = 10
@@ -35,6 +36,8 @@ const Feed = () => {
3536

3637
if (!parsedStorageData?.feedItems?.length) {
3738
loadMoreItems()
39+
} else {
40+
getWindowScrollY()
3841
}
3942
}, [loadMoreItems])
4043

src/hooks/useSetWindowScrollY.ts

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
'use client'
2+
3+
import { useEffect } from 'react'
4+
import { setItemInSessionStorage } from '@/utils/setItemInSessionStorage'
5+
6+
export const useSetWindowScrollY = () => {
7+
useEffect(() => {
8+
const onScroll = () => {
9+
setItemInSessionStorage('scrollY', window.scrollY)
10+
}
11+
12+
window.addEventListener('scroll', onScroll)
13+
14+
return () => window.removeEventListener('scroll', onScroll)
15+
}, [])
16+
}

src/utils/getWindowScrollY.ts

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
import { getItemFromSessionStorage } from '@/utils/getItemFromSessionStorage'
2+
3+
export const getWindowScrollY = () => {
4+
const parsedStorageData = getItemFromSessionStorage()
5+
6+
const scrollY = parsedStorageData?.scrollY || 0
7+
8+
const scrollToPosition = () => {
9+
window.scrollTo({ top: scrollY, left: 0, behavior: 'smooth' })
10+
}
11+
12+
requestAnimationFrame(() => {
13+
setTimeout(scrollToPosition, 0)
14+
})
15+
}

0 commit comments

Comments
 (0)