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.
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.
replace this
source={uri: this.state.img}
with
source={{uri: this.state.img}} // it will work if path is proper
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
Related
I'm trying to make an app that takes a picture and then returns the list of objects detected on that image. the code below is the whole code i'm using. i've changed the url of the api to 'insert api url here' just incase some troll find this post and spams the api with requests but i've made sure that the api url i'm using the correct one as i've tested it on postman and just copy pasted the api url.
import React, { useState, useEffect, useRef } from "react";
import { Text, View, StyleSheet, TouchableOpacity, Image } from "react-native";
import Constants from "expo-constants";
import { Camera, CameraType } from "expo-camera";
import * as MediaLibrary from "expo-media-library";
import { MaterialIcons } from "#expo/vector-icons";
import Button from "./src/components/Button";
import axios from "axios";
export default function App() {
const [hasCameraPermission, setHasCameraPermission] = useState(null);
const [image, setImage] = useState(null);
const [type, setType] = useState(Camera.Constants.Type.back);
const [flash, setFlash] = useState(Camera.Constants.FlashMode.off);
const cameraRef = useRef(null);
useEffect(() => {
(async () => {
MediaLibrary.requestPermissionsAsync();
const cameraStatus = await Camera.requestCameraPermissionsAsync();
setHasCameraPermission(cameraStatus.status === "granted");
})();
}, []);
const takePicture = async () => {
if (cameraRef) {
try {
const data = await cameraRef.current.takePictureAsync();
console.log(data);
setImage(data.uri);
} catch (error) {
console.log(error);
}
}
};
const savePicture = async () => {
if (image) {
try {
const asset = await MediaLibrary.createAssetAsync(image);
axios
.post("insert api url here", {
Imagee: image,
})
.then((response) => {
console.log(response);
})
.catch((error) => {
console.log(error);
});
alert("done");
setImage(null);
console.log("saved successfully");
} catch (error) {
console.log(error);
}
}
};
if (hasCameraPermission === false) {
return <Text>No access to camera</Text>;
}
return (
<View style={styles.container}>
{!image ? (
<Camera
style={styles.camera}
type={type}
ref={cameraRef}
flashMode={flash}
>
<View
style={{
flexDirection: "row",
justifyContent: "space-between",
paddingHorizontal: 30,
}}
>
<Button
title=""
icon="retweet"
onPress={() => {
setType(
type === CameraType.back ? CameraType.front : CameraType.back
);
}}
/>
<Button
onPress={() =>
setFlash(
flash === Camera.Constants.FlashMode.off
? Camera.Constants.FlashMode.on
: Camera.Constants.FlashMode.off
)
}
icon="flash"
color={flash === Camera.Constants.FlashMode.off ? "gray" : "#fff"}
/>
</View>
</Camera>
) : (
<Image source={{ uri: image }} style={styles.camera} />
)}
<View style={styles.controls}>
{image ? (
<View
style={{
flexDirection: "row",
justifyContent: "space-between",
paddingHorizontal: 50,
}}
>
<Button
title="Re-take"
onPress={() => setImage(null)}
icon="retweet"
/>
<Button
type="submit"
title="Save"
onPress={savePicture}
icon="check"
/>
</View>
) : (
<Button title="Take a picture" onPress={takePicture} icon="camera" />
)}
</View>
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: "center",
paddingTop: Constants.statusBarHeight,
backgroundColor: "#000",
padding: 8,
},
controls: {
flex: 0.5,
},
button: {
height: 40,
borderRadius: 6,
flexDirection: "row",
alignItems: "center",
justifyContent: "center",
},
text: {
fontWeight: "bold",
fontSize: 16,
color: "#E9730F",
marginLeft: 10,
},
camera: {
flex: 5,
borderRadius: 20,
},
topControls: {
flex: 1,
},
});
The part where it makes a post request the code snippet below.
so what i'm trying to do is store the uri of the image using state and then sending that uri
to the api using axios. i've made sure that the api is working on postman before testing it on my react native code but somehow i keep getting
[AxiosError: Request failed with status code 400]
I searched online as to what error 400 means and it says that it is an error caused by an invalid request which i find weird as the url is correct and i've done what every blog post or documentation axios has on post request has shown me.
const savePicture = async () => {
if (image) {
try {
const asset = await MediaLibrary.createAssetAsync(image);
axios
.post("insert api url here", {
Imagee: image,
})
.then((response) => {
console.log(response);
})
.catch((error) => {
console.log(error);
});
alert("done");
setImage(null);
console.log("saved successfully");
} catch (error) {
console.log(error);
}
}
};
I'm using react-native. I want to change the text data in Render according to the data I have taken in MYSQL. When ItemDURUM = 0, it says Order Pending, and when itemDURUM = 1, it says Order Confirmed. At the moment 0 and 1 value is waiting for the text value of the order is waiting. What is the problem? Now I'm pulling variable 0 and 1 from MYSQL without problems
export default class usrFirst extends React.Component {
import React, { Component } from "react";
import { Text } from 'react-native';
import { Cell, Section, TableView } from 'react-native-tableview-simple';
constructor(props) {
super(props)
this.state = {
itemDURUM:[]
}
responseMUSTERISIPARISDURUM() {
fetch('http://....php', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
BOYLAM: this.state...,
ENLEM: this.state....
})
}).then((response) => response.text())
.then((responseJson) => {
if(responseJson.length > 0)
{
this.setState({itemDURUM : responseJson});
}
}).catch((error) => {
console.error(error);
});
}
render() {
return (
<Cell cellStyle="RightDetail" title=<Text style={{color:'#00a7c0',fontWeight: "bold"}}>Durum</Text> detail= { this.state.itemDURUM === '0'? <Text style={{color:'#0094ff',fontWeight: "bold"}}>Order Pending</Text>: <Text style={{color:'#ff1706',fontWeight: "bold"}}>Order Confirmed</Text>} />
}
}
Your render method has some issues. I'm not sure where you call responseMUSTERISIPARISDURUM but try to change your render method to
render() {
return (
<Cell
cellStyle="RightDetail"
title={<Text style={{ color: '#00a7c0', fontWeight: "bold" }}>Durum</Text>}
detail={
this.state.itemDURUM === '0'
? <Text style={{ color: '#0094ff', fontWeight: "bold" }}>Order Pending</Text>
: <Text style={{ color: '#ff1706', fontWeight: "bold" }}>Order Confirmed</Text>
}
/>
)
}
I am building an App and referring this link
i implemented same code for my App, but i am getting error "Cannot read the property 'getSelectedItemsExt' of undefined".
One more error is "submit" button is also not showing up. I have tried all the ways but failed.
import React, { Component } from 'react';
import { AppRegistry, StyleSheet, TextInput, View, ListView, Alert, Button, Platform, ToastAndroid, TouchableOpacity, ActivityIndicator, Text, Picker, ScrollView }
from 'react-native';
import { StackNavigator } from 'react-navigation';
import MultiSelect from 'react-native-multiple-select';
class manage_publishers extends Component {
static navigationOptions = {
title: 'Manage Publishers',
};
constructor() {
super()
this.state = {
isLoading: true,
selectedPublishers1:[],
publishersByCategory: [],
publishersByClient: [],
publishersByGroup: [],
dataSource:[]
}
}
componentDidMount()
{
const base64 = require('base-64');
fetch('APIURL'+this.props.navigation.state.params.id,
{
method: 'GET',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
"Authorization": "Basic " + base64.encode("ABC:XYZ")
}
}).then((response) => response.json()
)
.then((responseJson) => {
this.setState({
categories: responseJson.PublisherByCategory,
}, function () {
});
})
.catch((error) => {
console.log("error in category");
console.log(error);
});
}
onSelectedPublishersByCategoryChange = (publishersByCategory) => {
console.log(publishersByCategory);
this.setState({ publishersByCategory });
}
render() {
const { navigate } = this.props.navigation;
if (this.state.isLoading) {
return (
<View style={{ flex: 1, paddingTop: 20 }}>
<ActivityIndicator />
</View>
);
}
return ([
<View style={{flex: 1,paddingTop: (Platform.OS === 'ios') ? 20 : 20, padding: 5}}>
<Text style={{ padding: 5, fontSize: 35, backgroundColor: '#2196F3', marginBottom: 7 }}>
Manage Publishers
</Text>
<MultiSelect
items={this.state.categories}
uniqueKey="id"
ref={(component) => { this.multiSelect = component }}
onSelectedItemsChange={this.onSelectedPublishersByCategoryChange}
selectedItems={this.state.publishersByCategory}
selectText="Publishers by Category"
searchInputPlaceholderText="Search Publisher..."
onChangeInput={ (text)=> console.log(text)}
altFontFamily="ProximaNova-Light"
tagRemoveIconColor="#CCC"
tagBorderColor="#CCC"
tagTextColor="#CCC"
selectedItemTextColor="#CCC"
selectedItemIconColor="#CCC"
itemTextColor="#000"
displayKey="name"
searchInputStyle={{ color: '#CCC' }}
submitButtonColor="#CCC"
submitButtonText="Submit"
/>
</View>,
<View>
{this.multiSelect.getSelectedItemsExt(selectedItems)}
</View>
]);
}
}
});
module.exports = manage_publishers;
Please have a look at this and provide me solution, I'll be very thankful .
I had that same issue, and I solved adding a AND condition:
{this.multiSelect && this.multiSelect.getSelectedItemsExt(selectedItems)}
If you are using functional components you can do like this,
create ref like this,
const multiSelect = useRef(null)
Access the getSelectedItemsExt function like this,
<View>
{multiSelect.current && multiSelect.current.getSelectedItemsExt &&
multiSelect.current.getSelectedItemsExt(countries)}
</View>
It happened because you called a method before the reference has been set.
Use this code:
<View>
{ this.multiSelect ? this.multiSelect.getSelectedItemsExt(selectedItems) : null}
</View>
Reference to this issue:
https://github.com/toystars/react-native-multiple-select/issues/58#issuecomment-364136438
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',
}
});
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.
'use strict';
import React, {Component} from 'react';
import {
StyleSheet,
Text,
View,
TextInput,
Image
} from 'react-native';
var Forecast=require('./Forecast');
const APIKEY = "API KEY";
var WeatherProject = React.createClass({
//if you want to have a default zip code, 넌 여기에 넣을 수 있다.
getInitialState(){
return {
zip:'', //우편 번호
forecast: null
};
},
_handleTextChange(event){
var zip= event.nativeEvent.text;
this.setState({zip:zip});
fetch('http://api.openweathermap.org/data/2.5/weather?zip='
+zip+'.KR&units=metric&APPID='+APIKEY)
.then((response) => response.json())
.then((responseJSON) => {
this.setState({
forecast: {
main: responseJSON.weather[0].main,
description: responseJSON.weather[0].description,
temp: responseJSON.main.temp
}
});
})
.catch((error) => {
console.warn(error);
});
},
render(){
var content = null;
if( this.state.forecast!==null){
content = <Forecast
main={this.state.forecast.main}
description={this.state.forecast.description}
temp={this.state.forecast.temp}/>;
}
return(
<View style={styles.container}>
<Image
source = {require('./img/flower.jpeg')}
resizeMode='cover'
style={styles.backdrop}>
<View style={styles.overlay}>
<View style={styles.row}>
<Text style={styles.mainText}>
Current weather for
</Text>
<View>
<TextInput
style={styles.zipCode}
returnKeyType='go'
onSubmitEditing={this._handleTextChange}/>
</View>
</View>
{content}
</View>
</Image>
</View>
);
}
});
var baseFontSize = 16;
var styles = StyleSheet.create({
container: {
flex: 1,
alignItems: 'center',
paddingTop:5
},
backdrop: {
flex:1,
flexDirection:'column'
},
overlay:{
paddingTop:5,
backgroundColor:'#000000',
opacity:0.5,
flexDirection:'column',
alignItems:'center'
},
row:{
flex:1,
flexDirection:'row',
flexWrap:'nowrap',
alignItems:'flex-start',
padding:30
},
zipCode:{
width:70,
height:30,
marginLeft:5,
backgroundColor:'#FFFFFF',
fontSize:20,
padding:0,
color: '#000000'
},
mainText:{
flex:1,
fontSize:baseFontSize,
color:'#FFFFFF'
}
});
module.exports=WeatherProject;
In _handleTextChange(event) function
.then((response) => response.json())
.then((responseJSON) => {
this.setState({
forecast: {
main: responseJSON.weather[0].main,
description: responseJSON.weather[0].description,
temp: responseJSON.main.temp
}
});
})
in this code, TypeError: undefined is not an object(evaluating 'responseJSON.weather[0]') There is an error.. why this error occuered?
How can I exchange this code to execute normally?
Your error is occurring because you have left out a valid API key to query against the OpenWeatherMap API. The response that comes back for what you have written is:
{"cod":401, "message": "Invalid API key. Please see http://openweathermap.org/faq#error401 for more info."}
Following this link will explain the requirement to set up an account and create an API key to use this service.
I created an account and API key with OpenWeatherMap, used your code sample, popping in a simple stateless component to dump out the props passed in to the Forecast component to verify this is all you need to correct your error.