Ad

Fetching Dynamic Images In Carousel In React Native

I am using react-native-image-gallery. In which url's of those images are already given in state in images array. But I want to load these images dynamically which I am fetching from API as shown in code. I am able to save those paths in state but, to show those images it requires domain name that is https://xyz.in/. On which I am stuck how can I show those dynamically fetched images.

Please help.

code:

  constructor(props) {
    super(props);
    this.state = {
      images: [
          { source: { uri: 'http://i.imgur.com/30s12Qj.jpg' } },
          { source: { uri: 'http://i.imgur.com/4A1Q49y.jpg' } },
          { source: { uri: 'http://i.imgur.com/JfVDTF9.jpg' } },
          { source: { uri: 'http://i.imgur.com/Vv4bmwR.jpg' } }
      ],
      fetched_images:[]
    };
  }


  async componentDidMount() {
      return fetch(`https://xyz.in/api/shop/username`,
    {
      method: "GET",
      headers: {
        'Authorization': `JWT ${DEMO_TOKEN}`
      }
    })
      .then((response) => response.json())
      .then((responseJson) => {
        this.setState({
          fetched_images: responseJson.all_images,
        });
    })
  }



  render() {
    return (
      <View>
         <Gallery
            style={{ height:300, width:'100%', backgroundColor: '#696969'}}
            images={this.state.images}
            errorComponent={this.renderError}
            onPageSelected={this.onChangeImage}
            initialPage={0}
          />
      </View>
    );
  }

json data:

"all_images": [
    {
        "image": "/media/All%20Product%20Images/20150415_093955_2.jpg"
    },
    {
        "image": "/media/All%20Product%20Images/amshoe.jpg"
    },
    {
        "image": "/media/All%20Product%20Images/ckramii.jpg"
    }
]
Ad

Answer

You can format your images by making a formatter function

const DomainName = 'https://xyz.in'

const formatImages = (images) => {
  return images.map(image => {
    return {source: {uri : `${DomainName}/${image}`}}
  })
}

.then((responseJson) => {
   const formattedImages = this.formatImages(responseJson.all_images)
   this.setState({
     fetched_images: formattedImages,
   });

 <Gallery
     ...// Other props
     images={this.state.fetched_images}
  />
Ad
source: stackoverflow.com
Ad