Reputation: 538
My <Image/>
remains blank even though I am console logging the URI value.
I am getting the URI from an API. The URI I'm getting is definitely https as well.
My code looks like this:
constructor(props){
super(props)
this.state = {
img: ''
}
}
componentDidMount() {
this.getImage(this.props.id)
}
getImage(id){
_this = this;
fetch(`someURL${userId}`, {
method: 'get',
headers: { Accept: 'application/json', 'Content-Type': 'application/json' },
})
.then(response => response.json())
.then((responseJson) => {
_this.setState({
img: responseJson.pic_url,
});
});
}
render() {
if (this.state.img) {
return (
<Image
resizeMode="cover"
style={{height: 50, width: 50}}
source={{uri: this.state.img}}
/>
}
return(
<View/>
)
}
If I just put the link into the URI directly like source={{uri: 'https://my-link'}}
it works. I need to be able to use state though b/c the link is coming from my api.
Upvotes: 3
Views: 2571
Reputation: 8542
I've created a snack expo with the following code:
import React, { Component } from 'react';
import { Image, Text, View, StyleSheet } from 'react-native';
import { Constants } from 'expo';
export default class App extends Component {
constructor() {
super();
this.state = {
imageUri: '',
};
}
componentWillMount() {
const _this = this
fetch('https://jsonplaceholder.typicode.com/photos/1')
.then(res => res.json())
.then(json => {
_this.setState({
imageUri: json.url.replace('http', 'https')
});
})
}
render() {
return (
<View style={styles.container}>
<Text style={styles.welcome}>
Image Test!
</Text>
{
this.state.imageUri ? (
<Image
resizeMode="cover"
source={{uri: this.state.imageUri}}
style={{height: 200, width: 200}}
/>
) : null
}
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: 'center',
justifyContent: 'center',
paddingTop: Constants.statusBarHeight,
backgroundColor: '#ecf0f1',
},
});
And it works just fine. The url that I get from the API is http, so I had to change it to https because it wouldn't work otherwise. Maybe that is your problem.
Upvotes: 2
Reputation: 396
So you are actually getting the response from your API? Did you print your URL inside your fetch method?
You don't need _this = this; as arrow functions are already binding this. However I think it shouldn't be a problem.
You have a mistake in your fetch.then It should be:
.then( (response) => response.json())
You missed the brackets around response
Upvotes: 0
Reputation: 6223
replace this
source={uri: this.state.img}
with
source={{uri: this.state.img}} // it will work if path is proper
Upvotes: 1