简体   繁体   中英

React Native Deck Swiper

I am trying to make a GET request to an enpoint using the two functional components below to display in my react native deck swipper

 //using fetch
const getDataUsingFetch = () => {
 fetch(latestNews+ApiKey)
   .then((response) => response.json())
   .then((responseJson) => {
     // set the state of the output here
       console.log(responseJson);
    setLatestNews(responseJson);
   })
   .catch((error) => {
     console.error(error);
   });
}

  //using anxios
  //asynchronous get request call to fetech latest news
const getDataUsingAnxios = async () => {

    //show loading
    setLoading(true);
    setTimeout(async () => {
      //hide loading after the data has been fetched
    setLoading(false);
    try {
      const response = await axios.get(latestNews+ApiKey);
      setLatestNews(response.data);
                setLoading(false);
        console.log(getLatestNews);
    } catch (error) {
      // handle error
      alert(error.message);
      }
    }, 5000);
};

Data returned when logged from console:

Array [
  Object {
    "category_id": "8",
    "content": "Hi",
    "created_at": "2020-11-12T12:43:03.000000Z",
    "featured_image": "splash-background_1605184983.jpg",
    "id": 19,
    "news_url": "doerlife.com",
    "title": "I m good how about you",
    "updated_at": "2020-11-12T12:43:03.000000Z",
  }....]

I now save the data into a state array

const [getLatestNews, setLatestNews] = useState([]);

Here is my swipper(some code ommited - not necessary)

  <Swiper
    ref={useSwiper}
    //cards={categoryID(docs, "2")}
    cards={getLatestNews}
    cardIndex={0}
    backgroundColor="transparent"
    stackSize={2}
    showSecondCard
    cardHorizontalMargin={0}
    animateCardOpacity
    disableBottomSwipe
    renderCard={(card) => <Card card={card} />}
    .....

When I try to access any data in the array from my Card reusable component, eg card.featured_image

I WILL GET THIS ERROR - TypeError: undefined is not an object (evaluating 'card.featured_image') . PLEASE CAN SOMEONE HELP ME.

//Card reusable component for deck swipper
import React from 'react'
import { View, Text, Image, ImageSourcePropType } from 'react-native'
import styles from './Card.styles'
const Card = ({ card }) => (
  <View activeOpacity={1} style={styles.card}>
    <Image
      style={styles.image}
      source={card.featured_image}
      resizeMode="cover"
    />

    <View style={styles.photoDescriptionContainer}>
      <Text style={styles.title}>{`${card.title}`}</Text>
      <Text style={styles.content}>{`${card.content}`}</Text>
      <Text style={styles.details}>
        Swipe Left to read news in details
      </Text>
    </View>
  </View>
);
export default Card

I've done something similar to this before so I think I can help a bit. The problem here is that your getLatestNews state has not been updated yet before the cards render. You can fix the problem by having another state called "isDataReturned". Then, have a useEffect that triggers whenever getLatestNews 's length changes. If getLatestNews 's length is > 0, then you can set isDataReturned to be true and render the deck only when isDataReturned is true.

Here's a code sample that I made:

const [getLatestNews, setLatestNews] = useState([]);
const [dataIsReturned, setDataIsReturned] = useState(false)

  useEffect(() => {
    const fetchData = async () => {
      const result = await axios(
        'https://cat-fact.herokuapp.com/facts',
      );
      setLatestNews(result.data);
    };

    fetchData();
  }, []);

  useEffect(() => {
    if (getLatestNews.length > 0) {
      setDataIsReturned(true)
    } else {
      setDataIsReturned(false)
    }
  }, [getLatestNews.length])

    if( dataIsReturned === true) {
      return (
      <View style={styles.container}>
         <Swiper
            cards={getLatestNews}
            renderCard={(card) => {
                return (
                  <View style={styles.card}>
                    <Text>{card.text}</Text>
                  </View>
                    
                )
            }}
            onSwiped={(cardIndex) => {console.log(cardIndex)}}
            onSwipedAll={() => {console.log('onSwipedAll')}}
            cardIndex={0}
            backgroundColor={'#4FD0E9'}
            stackSize= {3}>
        </Swiper>
    </View>)
    } else {
     return(<Text>Loading</Text>)
    }

In the renderCard attribute, i changed it from

 renderCard={(card) => <Cardz card={card} />}

to

 renderCard={(card) => (card && <Cardz card={card} />) || null}

and it worked.

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