skip to Main Content

I’m doing react-native project with expo + supabase.

From its QuickStart docs, (https://supabase.com/docs/guides/with-expo#launch)

import 'react-native-url-polyfill/auto'
import { useState, useEffect } from 'react'
import { supabase } from './lib/supabase'
import Auth from './components/Auth'
import Account from './components/Account'
import { View } from 'react-native'
import { Session } from '@supabase/supabase-js'

export default function App() {
  const [session, setSession] = (useState < Session) | (null > null)  // <-- what is this?

  useEffect(() => {
    setSession(supabase.auth.session())

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

  return (
    <View>
      {session && session.user ? (
        <Account key={session.user.id} session={session} />
      ) : (
        <Auth />
      )}
    </View>
  )
}

I can’t figure out how this useState works.

I know that | is bit-wise OR operator, but how does this work with useState?

2

Answers


  1. This would happen when you paste typescript code into a .js file and your editor tries to format it and fails miserably.

    I think the code actually intended to be this.

    const [session, setSession] = useState<Session|null>(null);  
    

    The extra brackets and space was added by your editor. VSCode does this for instance.

    The above statement means that session is a state variable which can be of type Session or null. And you initialise it with the value null.

    Here is a link to help you use TS with useState.

    Login or Signup to reply.
  2. You have mistake in useState here, try below code

    const [session, setSession] = (useState <Session | null>(null);  // updated here <Session | null> 
    

    is the interface which is used in typescript, For easy to use remove the Interface if you don’t understand.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search