Home > Mobile >  Special case of useState, what is this?
Special case of useState, what is this?

Time:08-16

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?

CodePudding user response:

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.

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

You should read up on Typescript with react hooks.

CodePudding user response:

You have mistake in useState here, try below 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 u don't understand.

  • Related