简体   繁体   中英

How check state values(obj value) conditionally in react native

I need to check state value conditionally, I fetch user data from firestore as follow

 const[userdata,setUserdata]=useState()

 const fetchCard = async()=>{
       // user
       const uRef = query(doc(db,'users',user.uid))
     await getDoc(uRef)
       .then((snapshot)=>{setUserdata(snapshot.data())})
       .catch((error)=>{
          alert(error)
      })

  console.log("here",userdata)
}

it get user data as objects

here Object {
  "age": "25",
  "displayName": "ghd",
  "gender": "female",
  "id": "E8R52y6dD8XI3shXhnhS9pVzUpe2",
  "interestIn": "male",
  "job": "gdh",
  "photo": "https://firebasestorage.googleapis.com/v0/b/match-me-now.appspot.com/o/images%2FE8R52y6dD8XI3shXhnhS9pVzUpe2%2FprofilePicture.jpeg?alt=media&token=9084cdcb-beb7-44d3-8ab9-98e193955e75",
  "timestamp": Object {
    "nanoseconds": 755000000,
    "seconds": 1639913879,
  },
}

but I need check this values conditionally when this value has no value, to handle error. because I will use this value in useEffect,

 useEffect(()=>{
     fetchCard()
  
   console.log("in effect",userdata.age)
    
     
    },[])
  

if there is no object value in fetchCard, this will cause error in useEffect when call value from useEffect. So I want to check userdata value has or not. if array value, just check with const newdata = userdata.length > 0? userdata: ["no"] const newdata = userdata.length > 0? userdata: ["no"]

but how can check this object values has or not? need help.

You can use Object.keys to check if your object is empty. You can check this link for more options.

useEffect(() => {
  if(userdata){
   if(Object.keys(userdata).length == 0){
     //if empty
     }else{
     //not emmpty
    }
   }
}, [userdata])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM