Next.js Discord

Discord Forum

Issue with state updates

Unanswered
Asiatic Lion posted this in #help-forum
Open in Discord
Asiatic LionOP
In the component below I'm having the issue where it flashes briefly the "complete-profile" component which should only show if the user doesn't exist. So basically for a brief moment the state userExists is being set to false. I'm not sure why.

'use client'

import React, { useState, useEffect } from 'react'
import { useSession } from 'next-auth/react'
import Link from 'next/link'
import { checkUser } from '../lib/dynamo_safe'
import CompleteProfile from './CompleteProfile'

export interface User {
email: string
name: string
image?: string
}

function Dashboard() {
const {data: session} = useSession()
const currentUser = session?.user as User
const [userExists, setUserExists] = useState<Boolean | null>(null)
useEffect(() => {
if (session && currentUser) {
fetch('/api/user', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
}
, body: JSON.stringify({email: currentUser.email, name: currentUser.name} as User )
})
.then((response) => response.json())
.then((data) => {
if (data.userExists === true) {
setUserExists(true)
} else {
setUserExists(false)
}
})
} else {
console.log('no session')
}
}, [session, currentUser]);
{if (session && session.user && userExists) {
return (
<div>
<p className="text-2xl font-bold">Welcome {session.user.name}!</p>
<p className="text-xl">Email: {session.user.email}</p>
</div>
)
} else if (session && session.user && !userExists) {
return <CompleteProfile/>
} else if (session && session.user && userExists === null) {
return <p>Loading...</p>
} else {
return <p>Loading...</p>}

}}

export default Dashboard

1 Reply

Wuchang bream
The state is intiialized as null. Then you use an useEffect to set userExists to true or false. Untill the api request is made and completed, userExists will remain false, which will meet the condition to show CompleteProfile. Maybe create a state named showCompleteProfile, default it to false, and set to true if needed. Then instead of userExists, show CompleteProfile based on the state showCompleteProfile.