I'm trying to create a social media app as a project. I have two pages: posts.js
and [id].js
.
posts.js
<div
className={styles.userDetails}
onClick={() => {
router.push({ pathname : `/user/${props.user._id}`})
}}
>
</div>
When user clicks on this div
, user will be redirected to [id].js
. In this case, id
retrieved from router is used as userId
. But when user want to view his own profile, usedId
should be retrieved from localStorage. When the user logs in, user's id will be saved to localStorage.
const [userId, setUserId] = useState()
const getUserData = async () => {
try {
if (router.query.id != undefined ) {
setUserId(router.query.id)
} else {
setUserId(getUser())
}
const res = await instance.get(`/user/${userId}`)
setUser(res.data)
} catch(e) {
console.log(e)
}
useEffect(() => {
getUserData()
getPosts()
}, [router.query])
I tried to set userId
using if condition. But at the time of loading the page, value of router.query.id
is undefined. It takes a bit to retrieve the id from router. Due to this I get userId
= undefined.
I have made a condition like if (router.push.id != "undefined"
, but it doesn't work.