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
327 views
in Technique[技术] by (71.8m points)

reactjs - 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, e.g 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

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

1 Reply

0 votes
by (71.8m points)

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>)
    }

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

1.4m articles

1.4m replys

5 comments

57.0k users

...