简体   繁体   中英

Pass a promise to a component React Native

I'm filling my data array with an API call like so

 const getData = async () => {
    const response = await fetch(
      "URL"
    );
    var data = await response.json();
    let arr = [];
    for (let i = 0; i < data.length; i++) {
      arr.push(data[i]);
    }
    return arr;
  };

How do i pass it to a react Native component, with it being a promise?

return(
 <View style={styles.container}>
      <Swiper
        cards={  getData } //Here
        renderCard={(card) => {
          return (
            <View style={styles.card}>
              <Text style={styles.text}>{card}</Text>
            </View>
          );
        }}
       
      </Swiper>
);

Put the fetch function in a useEffect in the parent component and make arr a state variable

const [arr, setArr] = useState([])
useEffect(()=>{
  const getData = async () => {
      const response = await fetch(
        "URL"
      );
      var data = await response.json();
      setArr(data)
  }
  getData();
},[])
return (
 <View style={styles.container}>
      <Swiper
        cards={arr} //Here
        renderCard={(card) => {
          return (
            <View style={styles.card}>
              <Text style={styles.text}>{card}</Text>
            </View>
          );
        }}
      </Swiper>
  </View>)
     

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