Home > front end >  getting first elements undefined using useEffect react
getting first elements undefined using useEffect react

Time:12-09

enter image description here

Hi I keep getting undefined for the first element then I get full element is there any way to get the element the first time?

const [me,{data}]=useMutation(ME_MUTATON)
const User = data?.me

console.log(,User)

console.log("fgf",User?.userName)

useEffect(() => {

    me()

  
}, [me]);

(Hi I keep getting undefined for the first element then I get full element is there any way to get the element at the first time? )

CodePudding user response:

Why you don't put your data in useEffect like this ?

const [me, { data }] = useMutation(ME_MUTATON);
const [user, setUser] = useState();

useEffect(() => {
    me();
}, [me]);

useEffect(() => {
  if(data && data.me && JSON.stringify(data.me) !== JSON.stringify(user)) {
    const User = data.me;
    console.log(User);
    console.log("Username: ", User.username);
    setUser(User);
  }
}, [data]);
  • Related