Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

useEffect causing render error when attempting to set state in app.js

I’ve got a useEffect in my app.js file, which attempts to set a ‘session’ state based upon the response from a function I’ve got.

const App = () => {

 const [session, setSession] = useState(null)

 useEffect(() => {
    supabase.auth.getSession()
    .then((response) => {
      setSession(response.data.session)
    })

    supabase.auth.onAuthStateChange((_event, session) => {
      setSession(session)
    })

  }, [session])

I then pass this state as a prop into my ‘Router’ component, like so:

<Route path="/dashboard/details" element={<PrivateRoute><DashboardDetails session={session}/></PrivateRoute>} />

Finally, in my component, I attempt to access the user’s id from the session data, and set it in ‘id’ state, passing props as a dependency in case the user’s id isn’t available on the first render:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

useEffect(() => {
  const id = props.session.user.id
  setId(id)
}, [props])

However, it’s returning the following error:

Uncaught TypeError: Cannot read properties of null (reading ‘user’)

I know for definite that the session.user.id is the correct path to access it, but I can’t figure out what I’m doing wrong here.

>Solution :

need to check if the user is undefined or not. use the ? operator

useEffect(() => {
  const id = props.session?.user?.id
  if(id) setId(id)
}, [props.session])
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading