Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
202 views
in Technique[技术] by (71.8m points)

React native app keeps returning undefined when fetching data from backend

I currently have a react native app with a nodeJS backend. I using a function to get the data from the backend, then using that data to conditional render a button in my app.

My problem is that as soon as the app loads i keep getting undefined then true and hence the functionality does not work due to the undefined value. Does anyone know why that might be happening?

Here is my code:

const [data,setData]=useState([]);
const [error, setError] = useState(false);
const [loading, setLoading] = useState(false);
const [refreshing, setRefreshing] = useState(false);
const [isEnabled, setIsEnabled] = useState(data.locked);
const [activated, setActivated] = useState(data.activated);

const loadData = async () => {
   setLoading(true);
   const response = await Api.getData();
   setLoading(false);
   if(refreshing) 
   setRefreshing(false);
   if (!response.ok){
      return setError(true); 
   }
   setError(false);
   setData(response.data)
   if(response.data.locked===true) 
     setIsEnabled(true);
};

useEffect(() => {
   loadData();
}, [data.locked]);

console.log(data.activated)

const activate = ()=>{
   setActivated(true);
}

return(
{activated != true ?
         <View style={{justifyContent:'flex-start',
                       alignItems:'flex-start',marginLeft:-10}}>
         <Button title='Activate' onPress={activate}/>
         </View>           
        :
        null
        }
)

data.activated prints out the following

 undefined
 undefined
 undefined
 undefined
 true
 true
 true
 true
 true

and the button is getting displayed when it's not supposed to.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
console.log(data.activated)

Will get called a few times before loadData is done so it will be undefined until setData is done setting data

EDIT: This is how I would have written the component:

const [loading, setLoading] = useEffect(true)
const [data,setData] = useEffect(null)

useEffect(()=>{loadData()},[])
useEffect(()=>{if(data){setLoading(false)},[data]}

return (
{!loading?<THE BUTTON>:null}
)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...