komikat
komikat

Reputation: 79

Not able to fetch image from API in React Native

I am a beginner on React Native and was working on an app that fetches text and images from my API and displays it on the screen. The text is displayed but the image is not displayed. No errors. I have only one main file : App.js with the API call being

  https://www.teanewsnetwork.com/api/fetcharticles.php?code=Me*z6Pcw9e1$CQ)YWgMlFe%nv(Hq)lhw&starting=0&limit=20 

App.js :

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
import React, { Component } from 'react';
import {
  View,
  Text,
  ActivityIndicator,
  ScrollView,
  StyleSheet,
  Image,
} from 'react-native';

import Img from 'react-image';

let li = 'https://www.teanewsnetwork.com/profileicons/';
let bean = 'azure.jpg';

export default class App extends Component {
  state = {
    loading: true,
    error: false,
    posts: [],
  };

  componentWillMount = async () => {
    try {
      const response = await fetch(
        'https://www.teanewsnetwork.com/api/fetcharticles.php?code=Me*z6Pcw9e1$CQ)YWgMlFe%nv(Hq)lhw&starting=0&limit=40'
      );
      const posts = await response.json();

      this.setState({ loading: false, posts });
    } catch (e) {
      this.setState({ loading: false, error: true });
    }
  };

  renderPost = ({ id, title, content, authorimage, authorname }, i) => {
    let b = { authorname };
    return (
      <View style={styles.postContent}>
        <Text>{authorname}</Text>
        <Image
          source={{
            uri: 'https://teanewsnetwork.com/profileicons/',
          }}
          style={{ width: 40, height: 40 }}
        />

        <Text style={styles.postauthor}>{title}</Text>
        <Text style={styles.postBody}>{content}</Text>
      </View>
    );
  };

  render() {
    const { posts, loading, error } = this.state;

    if (loading) {
      return (
        <View style={styles.center}>
          <ActivityIndicator animating={true} />
        </View>
      );
    }

    if (error) {
      return (
        <View style={styles.center}>
          <Text>Failed to load posts!</Text>
        </View>
      );
    }

    return (
      <ScrollView style={styles.container}>
        {posts.map(this.renderPost)}
      </ScrollView>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
  },

  postauthor: {
    flex: 1,
    borderBottomWidth: 1,
    borderBottomColor: '#EEE',
    paddingVertical: 25,
    paddingRight: 15,
  },

  postContent: {
    flex: 1,
    borderBottomWidth: 1,
    borderBottomColor: '#EEE',
    paddingVertical: 25,
    paddingRight: 15,
    left: 10,
  },
  postBody: {
    marginTop: 10,
    fontSize: 12,
    color: 'lightgray',
    left: 10,
  },
  center: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
  },
});

I want to display my images below every name which are to be taken from the link

 www.teanewsnetwork.com/profileicons/{{authorimage}}

Where {{authorimage}} is given in the API. But this doesn't seem to work. Thanks is advance!

Upvotes: 3

Views: 6520

Answers (2)

Murf
Murf

Reputation: 1719

You can use template literals in JavaScript. This will append the authtorimage to the end of the string.

<Image
        source={{
            uri: `https://teanewsnetwork.com/profileicons/${authorimage}`,
        }}
        style={{ width: 40, height: 40 }}/>

Template literals are enclosed by the back-tick (```) (grave accent) character instead of double or single quotes. Template literals can contain placeholders. These are indicated by the dollar sign and curly braces (${expression}). The expressions in the placeholders and the text between them get passed to a function.

Upvotes: 3

bjupreti
bjupreti

Reputation: 353

You are doing it very correctly except in two places which I have pointed below:
- While importing the react native components you are also doing:

import Img from 'react-image';

This is unnecessary as react native itself provides Image components.
- Also, you need to pass value of authorimage in source of the image as:

<Image 
  source= {{
    uri: `https://teanewsnetwork.com/profileicons/${authorimage}`,
  }}
  style={{height: 40, width: 40}}
/>

Here, is the link of working snack. If you want to learn more about how images works in react native, you can visit this link.

Upvotes: 1

Related Questions