2

I am new to React Native! And having problems with properly loading the image off the JSON that I get from JsonPlaceHolder API. I set the state of the photos and the titles. The titles were able to load, however, photos were not be able to load properly. I did search and there are suggestions to replace http to https call would fix it. But No luck here. Please help! And Thank in Advance!

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

export default class App extends Component {
  constructor(props){
  super(props);
    this.state = {
      photos: '',
      titles: ''
    };
  }

  componentWillMount(){
    this.fetchData();
  }

  fetchData = async () => {
    let response = await fetch('http://jsonplaceholder.typicode.com/photos/1');
    let json = await response.json();
    this.setState({titles: json.title, photos: json.url.replace('http','https')});
  };

render() {
    console.log(this.state.photos)
    return (
      <View style={styles.container}>
        <Image 
          source={{uri: this.state.photos}} 
          style={{height: 600, width: 600}}
          resizeMode= 'cover'
        />
        <Text>
          Title: {this.state.titles}
        </Text>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center',
    backgroundColor: '#ecf0f1',
  }
});

1 Answer 1

1

Hey so I ran your exact code except i replaced

this.setState({titles: json.title, photos: json.url.replace('http','https')});

with

this.setState( {
  title: json.title,
  photos: json.url,
} )

and it works fine for me, it simply gives me the error for not having an empty string as uri which is expected.

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

6 Comments

Am I missing something that the "this.state.photos" is not passing on properly inside of <Image source ={{ uri: this.state.photos }} /> in order for the image to load properly?
so state.photos was logging fine and the url was a valid one too. Although you should accommodate for when the url is blank( if the api is taking longer than the render). I suggest use a placeholder image if state.photos is blank or empty. That should get rid of the warning.
I quickly transfer it to my mac and it works on the ios emulator. I'll have to find out what's not working on my windows PC, expo & my Google XL phone. Thanks for the help! Much appreciated!
thats strange, just to let you know i tested it on windows with an android emulator sunning API 25.
i think its probably due to ansyc call.
|

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.