0

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.

Drew Reese
  • 165,259
  • 14
  • 153
  • 181
  • When the user views his own profile, you still redirect the same way, right, with the `/user/${props.user._id}`? – Youssouf Oumar Aug 14 '23 at 17:28
  • I have created the link to profile from navigation bar. There i have used to redirect to [id].js. Let me replace is with router push method – Unnikrishnan KJ Aug 14 '23 at 17:35
  • What I'm trying to understand is: on the detail page, if the user is viewing their own profile, there will not be an id in the URL, right? – Youssouf Oumar Aug 14 '23 at 17:44
  • 1
    Thank you for your valuable time sir. Now I have got solution for my problems. When user click view profile, router push method is used instead of – Unnikrishnan KJ Aug 14 '23 at 18:19

0 Answers0