Yefim Blokh
Yefim Blokh

Reputation: 85

Inability to get data from API react native

Hi so my main question is when making a api call to https://newsdata.io, i want to access the results method on the object the api returns. However react native is saying results is undefined. Why cant i see the data object but not the methods attached to the data variable.

import React from 'react' import { Text, View, Image } from 'react-native'

export const Feed = () => {
  async function  data() {
    const response = await fetch('https://newsdata.io/api/1/news?apikey=pub_11306c8c5e2932eab7155edacbc6339247174&q=web%203')
    const data = await response.json()
    const results = data.results;
    const imageURLDATA = results.forEach(element => {
      console.log(element.image_url)
    })
  }
  data()
  return (
    <View>
      <Text style={{fontSize: 40, fontWeight: "700", marginTop: 20}}>Feed</Text>
      {results.forEach(element => {
      <View>
        < Image source={{
          uri: `${element.image_url}`
        }}/>
        </View>
    })}
    </View>
  )
}

Upvotes: 0

Views: 286

Answers (1)

PhantomSpooks
PhantomSpooks

Reputation: 3540

You need to take the component lifecycle into consideration. Use useState to create a variable that trigger component rerenders and useEffect to call functions at certain events:

import React, { useState, useEffect } from 'react';
import { View, Image, Text } from 'react-native';

export const Feed = () => {
  const [feedData, setFeedData] = useState([]);
  async function getData() {
    // you may want to change your api key
    const response = await fetch(
      'https://newsdata.io/api/1/news?apikey=pub_11306c8c5e2932eab7155edacbc6339247174&q=web%203'
    );
    const data = await response.json();
    const results = data.results;
    setFeedData(results);
  }
  //will call provided function when items in array is updated
  useEffect(() => {
    console.log('Feed data updated')
    feedData.forEach((element) => {
      console.log(element.image_url);
    });
  }, [feedData]);
  // will call provided function once after first render
  useEffect(() => {
    getData();
  }, []);

  return (
    <View>
      <Text style={{ fontSize: 40, fontWeight: '700', marginTop: 20 }}>
        Feed
      </Text>
      {/*forEach returns null, map returns value*/}
      {feedData.map((element) => (
        <View>
          <Image
            source={{
              uri: `${element.image_url}`,
            }}
            // provide width to element or it wont render
            style={{width:100,height:100}}

          />
        </View>
      )
      )}
    </View>
  );
};
export default Feed;

Here's a demo

Upvotes: 1

Related Questions