-1

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?

Robert_dev
  • 19
  • 4
  • 1
    setUser changes the state and triggers a rerender. User will not be set until after that rerender. React is designed with a declarative style rather than the imperative you are assuming. – possum Sep 08 '22 at 08:53

2 Answers2

2

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])
Jay
  • 2,826
  • 2
  • 13
  • 28
0

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.

Sifat Amin
  • 1,091
  • 6
  • 15
  • Still not working, can you give me an example code please? I tried to display User in a h1 tag but i get an error in console that say: Uncaught TypeError: Cannot read properties of undefined,i also tried to reload the page and i get the same error. – Robert_dev Sep 08 '22 at 09:15