Reputation: 191
I'm making a small SNS app using React. (Gatsby.js)
What I want to do is to persist state in previous pages even when you go back with the browser. Like twitter or instagram, when you go to follow or follower page and visit more pages, you do not lose data when you go back. I can't find a single clue. Is it something to do with history api or routing?
There is also a User page and it contains some links to following/follower pages in my app. When a user reaches on a page, I am fetching API in useEffect hook using url params then store it to global state(recoil), show on the component. Here is a problem. When I visit user page and move forward to follower page, then visit another user page from there and move to his follower page, when I go back with the browser, they don't remember the global state (of course) and it'll get fetch data again which shows loading. Tried to clean data when unmounting because it shows previous data when you go to other page. Couldn't find the bast practice.
Probably it's nothing to do with global states (Recoil), somehow window
is remembering what was in the previous pages (and scroll position too)?
I'd appreciate any advice. Thank you.
React/GatsbyJS Router/Reach-router
Route
...
<PrivateRoute path="/user/:userId" component={UserPage} />
<PrivateRoute path="/:userId/follower" component={FollowerPage} />
...
UserPage
const UserPage = () => {
const { userId } = useParams()
const user = useRecoilValue(userProfileViewData)
const loading = useRecoilValue(loadingUserPage)
...
useEffect(() => {
... // fetch api to get user info
...// store it in global state -> userProfileViewData
}, [])
if(loading) return <div>Loading</div>
return (
<div>
<div>{user.name}</div>
...
<div onClick={() => navigate('/app/' + userId + '/follower')}>Follower</div>
...
</div>
)
}
export default UserPage
FollowerPage
const FollowerPage = () => {
const { userId } = useParams()
const [loading, setLoading] = useState(true)
const followerData = useRecoilValue(followers)
...
useEffect(() => {
...// api calls to get followers
...// store it in global state -> followers
}, [])
useEffect(() => {
return () => {
.. // I have a function to clean data here
}
}, [])
if(loading) {
return <div>loading....</div>
}
return (
<div>
<div>Follower</div>
<div>
{followerData.map(user => (
<div key={`user.id}>
<div onClick={() => navigate(`/app/user/` + user.id)}>
{user.name}
</div>
</div>
))}
</div>
</div>
)
}
export default FollowerPage
Upvotes: 1
Views: 1407