0

Hello everyone i got API data from but can't solve how to solve this problem , maybe any tips for the freshman?

Here, I attached screenshot of what i did already:

image

2
  • String literal require ${var_name} Commented Feb 13, 2021 at 5:55
  • i did even like this , but didnt work( Commented Feb 13, 2021 at 6:02

1 Answer 1

1

The image API you list doesn't return a URL. It returns JSON, just like your initial API response. So, you'll have to perform fetch requests for the images and store them, then refer to the URLs you got in your list. That'll require a bit more state.

Here's a working example:

export default function App() {
  const [data, setData] = React.useState(null)
  const [isLoading, setLoading] = React.useState(false)
  const [images, setImages] = React.useState({})
  
  React.useEffect(() => {
      fetch('https://dog.ceo/api/breeds/list/all')
        .then((response) => response.json())
        .then((json) => setData(Object.keys(json.message)))
        .catch((error) => console.error(error))
        .finally(() => setLoading(false));
    }, []);

  React.useEffect(() => {
    if (!data) { return; }
    data.forEach((dataItem,index) => {
      if (index > 5) { return; }
      let url = `https://dog.ceo/api/breed/${dataItem}/images`
      fetch(url)
        .then((response) => response.json())
        .then(json => {
          if (!json.message[0]) { return; }
          setImages(prevState => ({...prevState, [dataItem]: json.message[0]            }));
        })
    })
  },[data])

    
    return (
      <View style={styles.container}>
      {isLoading ? <ActivityIndicator/> : (
          <FlatList
            data={data}
            keyExtractor={({ id }, index) => index.toString()}
            renderItem={({ item }) => (
            <View>
              <Text>{item} </Text>
              {images[item] ?  <Image
               style={{width: 100, height: 100}}
                source={{
               uri: images[item],
               }}
              />  : null }
              <Text>Image: {images[item]}</Text>
            </View>)}
          />
      )
      }
      </View>
   );
}

https://snack.expo.io/5FjQnP1Xf

Note that in this example, I only get the first 5 images to avoid making a ton of API calls.

It's also not a particularly robust solution -- in the real world, you'd definitely want to do more error handling than I'm doing here, cache the images, etc -- this is just a basic proof-of-concept.

Sign up to request clarification or add additional context in comments.

1 Comment

yeah, i tried to make here all of the API calls, and it gave me an error of that it is lowing the APP and make sure to use Pure Components

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.