Why useState set don't work inside useEffect in react?How can i fix this?

Viewed 31

So this is my problem:

import sanityClient from '@sanity/client';

export const client = sanityClient({
  projectId: import.meta.env.VITE_APP_SANITY_PROJECT_ID ,
  dataset: 'production',
  apiVersion: '2022-09-08',
  useCdn: true,
  token: import.meta.env.VITE_APP_SANITY_TOKEN,
  ignoreBrowserTokenWarning: true
});

for this project i use sanity client

import { useState,useEffect } from 'react'
import {client} from './client'

function App() {
 const [User, setUser] = useState()

 useEffect(()=>{
    const getUserData=()=>{
       const query = `*[_type == "user" && _id == 'John']`;
       client.fetch(query).then((data)=>{
       console.log(data[0]) //return data as expected
       setUser(data[0])
       console.log(User) //return undefined
     })
   }
    getUserData()
 },[])

Why when i reload the page setUser don't work inside useEffect and return undefined?

2 Answers

You will. not get data instantly use new useEffect like this

import { useState,useEffect } from 'react'
import {client} from './client'

function App() {
 const [User, setUser] = useState()

 useEffect(()=>{
    const getUserData=()=>{
       const query = `*[_type == "user" && _id == 'John']`;
       client.fetch(query).then((data)=>{
       setUser(data[0])
     })
   }
    getUserData()
 },[])

 useEffect(()=>{
    if (User) {
       console.log(User)
    }
 },[User])

You wont get any log, but your code is correct. It's because setState(updater[, callback])
setState tells its children and the component needs to be rerendered. So you wont get immeditately the changed state value. If you console log before the useState, you'll see
at first its showing undefined but after rerendering you'll get the updated state value.

Related