I sent a post request to the server through API upon which I received the following response in JSON format (console.log screenshot):
Upon executing the following code, I was able to Display the response in an Alert dialog box:
uploadPhoto() {
RNFetchBlob.fetch('POST', 'http://192.168.1.102:8000/api/v1/reader/', {
Authorization: 'Bearer access-token',
otherHeader: 'foo',
'Content-Type': 'multipart/form-data',
}, [
{ name: 'image', filename: 'image.png', type: 'image/png', data: this.state.data },
]).then((response) => response.json())
.then((responseJson) => {
this.setState({
jsonData: responseJson
}, () => {
Alert.alert(" Vehicle Number Plate: " + responseJson.processed_text);
console.log(responseJson);
});
})
.catch((error) => {
console.error(error);
});
}
<TouchableOpacity
style={styles.buttonStyle}
onPress={this.uploadPhoto.bind(this)}>
<Text style={styles.btnTextStyle}> Process Image</Text>
</TouchableOpacity>
However, Since i am very new to React-Native development, i am unable to display the JSON data in the application other than in the alert dialog box. Following is my code:
Initializing the state of jsonData object through the constructor:
constructor() {
super();
this.state = {
imageSource: null,
data: null,
jsonData: []
};
}
Thenafter, the state of jsonData object is set (In detail: Code snippet above):
.then((response) => response.json())
.then((responseJson) => {
this.setState({
jsonData: responseJson
}
Finally, I used the component FlatList for displaying the data:
<View>
<Text>Display Response JSON Data</Text>
<FlatList
data={this.state.jsonData}
renderItem={({ item }) => <Text> {item.processed_text } </Text>}
/>
</View>
However, I am not able to see the output! How can I solve this problem?
Flatlist works on arrays. Your response should be an array like this:
[
{ processed_text: 'value1', owner: { fullname: 'alex' } },
{ processed_text: 'value2', owner: { fullname: 'john' } },
]
for more insights check Flatlist
Related
Update: How do I get an array (currentSchedule) within an array (response)?
I am trying to get the JSON object in "response" within the JSON code below. For instance, I want to get the title & description in "response", but it is not returning anything for me with the codes that I implemented below.
all.json
{"responseCode":200,
"responseMessage":"Channel Listing",
"response":[{
"id":395,
"title":"Title 1",
"description":"Description 1",
"currentSchedule":[{"eventId":"123456","title":"Hello Title"]}
}]
}
App.js
class App extends Component {
constructor(props){
super(props);
this.state = {
items: [],
isLoaded: false,
}
}
componentDidMount(){
fetch('/all.json')
.then(res => {
res.json()
})
.then(json => {
this.setState({
isLoaded: true,
items: [],
})
});
}
render() {
var { isLoaded, items } = this.state;
if(!isLoaded) {
return <div>Loading...</div>;
}
else {
return (
<div className="App">
<ul>
{items.map(item => (
<li key={item.id}>
Title: {item.title} | Description: {item.description}
</li>
))};
</ul>
</div>
);
}
}
}
export default App;
You need to assign response in your setState to view it, somthing like this
componentDidMount(){
fetch('/all.json')
.then(res => res.json())
.then(json => {
this.setState({
isLoaded: true,
items: json.response,
})
}).catch(console.log);
}
I have setup Vuex in Vue.js and using it to update the state. After building login functionality on it I am trying to store the token in localstorage but when I add localstorage to state it is throwing an error.
my current code:
import Vue from 'vue';
import Vuex from 'vuex';
import { getAPI } from '#/axios';
Vue.use(Vuex);
export default new Vuex.Store({
state: {
accessToken: JSON.parse(localStorage.getItem('accessToken')) || null,
APIData: '',
},
mutations: {
// eslint-disable-next-line camelcase
updateStorage(state, { access_token }) {
// eslint-disable-next-line camelcase
state.accessToken = access_token;
localStorage.setItem('accessToken', JSON.stringify(access_token));
// axios.defaults.headers.common.Authorization = `Bearer ${access_token.access_token}`;
// sessionStorage.setItem('accessToken', access_token);
},
destroyToken(state) {
state.accessToken = null;
},
},
getters: {
loggedIn(state) {
return state.accessToken != null;
},
},
actions: {
userLogin(context, usercredentials) {
return new Promise((resolve, reject) => {
getAPI.post('/login', {
email: usercredentials.email,
password: usercredentials.password,
})
.then((response) => {
context.commit('updateStorage', { access_token: response.data.access_token });
resolve();
console.log(response.data.access_token);
})
.catch((error) => {
reject(error);
});
});
},
userLogout(context) {
if (context.getters.loggedIn) {
context.commit('destroyToken');
}
},
},
});
Since you're receiving raw encoding and creating an object wrapper for it in this format:
{ access_token: 'eyJ0eX...' }
You shouldn't destructure it in the mutation payload. Pass the whole object to localStorage if you're going to use JSON.parse:
updateStorage(state, access_token) {
state.accessToken = access_token;
localStorage.setItem('accessToken', JSON.stringify(access_token));
},
I am trying to get picker values from the server to my react-native project. this is my JSON data. How do I fetch it for the picker component? I tried all d methods from web results. but I get only a blank screen. Kindly please help
{
"MFBasic": {
"SkinTones": "DARK,FAIR,VFAIR",
"Build": "SLIM,ATHLETIC,PLUMPY",
"Gender": "F,M,T",
"Genre": "ACTION,COMEDY,DRAMA",
"Languages": "ENG,HINDI,TAM",
"MediaModes": "ADS,MOVIES,SHORTFILMS",
"Tags": "BIKES,HOME,JEWELLARY"
},
"Result": "Successfully Loaded MF Basic Details",
"Code": 100
}
App.js
export default class App extends Component {
state = {
PickerValueHolder:[],
Gender:'',
}
componentDidMount() {
fetch('https://movieworld.sramaswamy.com/GetMFBasicDetails.php', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
}).then((response) => response.json())
.then((responseJson) => {
let PickerValueHolder = responseJson.MFBasic;
this.setState({ PickerValueHolder }); // Set the new state
}).catch((error) => {
console.error(error);
});
}
render() {
return (
<View style = {styles.MainContainer}>
{<Picker
selectedValue={this.state.Gender}
onValueChange={(itemValue, itemIndex) =>
this.setState({Gender:itemValue})} >
{ this.state.PickerValueHolder.map((item, key)=>
<Picker.Item label={item.Gender} value={item.Gender} key={key}/>
)}
</Picker>}
</View>
);
}
}
above code is my app.js file. but it returns nothing to the picker.help me please. Thank u.
Looking at the json from your API call
{
"MFBasic": {
"SkinTones": "DARK,FAIR,VFAIR",
"Build": "SLIM,ATHLETIC,PLUMPY",
"Gender": "F,M,T",
"Genre": "ACTION,COMEDY,DRAMA",
"Languages": "ENG,HINDI,TAM",
"MediaModes": "ADS,MOVIES,SHORTFILMS",
"Tags": "BIKES,HOME,JEWELLARY"
},
"Result": "Successfully Loaded MF Basic Details",
"Code": 100
}
The issue that is that you are trying to set a string where it needs an array. You can do it by doing something like this:
let genderString = responseJson.MFBasic.Gender;
let genderArray = genderString.split(',');
this.setState({ PickerValueHolder: genderArray });
let responseJson = {
"MFBasic": {
"SkinTones": "DARK,FAIR,VFAIR",
"Build": "SLIM,ATHLETIC,PLUMPY",
"Gender": "F,M,T",
"Genre": "ACTION,COMEDY,DRAMA",
"Languages": "ENG,HINDI,TAM",
"MediaModes": "ADS,MOVIES,SHORTFILMS",
"Tags": "BIKES,HOME,JEWELLARY"
},
"Result": "Successfully Loaded MF Basic Details",
"Code": 100
}
let genderString = responseJson.MFBasic.Gender;
let genderArray = genderString.split(',');
console.log(genderArray)
Because the items in your array are just strings you cannot access them by using item.Gender that won't work. You need to just access them using item.
I have created an example based on your code and implemented the change from above and fixed the Picker.Item component so it should render now. You can see the working code at the following snack https://snack.expo.io/#andypandy/picker-with-array-of-strings
import React from 'react';
import { Text, View, StyleSheet, Picker } from 'react-native';
import { Constants } from 'expo';
export default class App extends React.Component {
state = {
PickerValueHolder: [],
Gender: ''
}
componentDidMount () {
fetch('https://movieworld.sramaswamy.com/GetMFBasicDetails.php', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
}
}).then((response) => response.json())
.then((responseJson) => {
let genderString = responseJson.MFBasic.Gender;
let genderArray = genderString.split(',');
this.setState({ PickerValueHolder: genderArray });
}).catch((error) => {
console.error(error);
});
}
render () {
console.log(this.state.PickerValueHolder)
return (
<View style={styles.container}>
{<Picker
selectedValue={this.state.Gender}
onValueChange={(itemValue, itemIndex) =>
this.setState({ Gender: itemValue })} >
{ this.state.PickerValueHolder.map((item, key) =>
<Picker.Item label={item} value={item} key={key}/>
)}
</Picker>}
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
paddingTop: Constants.statusBarHeight,
backgroundColor: '#ecf0f1',
padding: 8
}
});
I'm working with a JSON rest API that has the following response:
// response
[
{
id: 1,
userId: 1,
start: "2018-01-01 10:15",
finish: "2018-01-01 12:20",
breakLength: 30
},
{
id: 2,
userId: 1,
start: "2018-01-02 10:15",
finish: "2018-01-02 18:20",
breakLength: 45
}
];
See below for code. Like my other functions, I am requesting a GET using fetch(). However, sometimes this function when called requests and responds with a 200, and sometimes it responds with a 400 bad request(Uncaught (in promise) SyntaxError: Unexpected token B in JSON at position 0) It seems very random when it happens. My server which the JSON Rest API is on is localhost:3000 and my application is on localhost:3001. I have used this same method for other JSON requests and they work perfectly. I am not sure why this one is having trouble? Thanks for your help!
Update: It seems as though the last Promise.all, setState is not being executed. The program is crashing on line .then(response => response.json()) in promise3.
Updated Code:
getShifts = (sessionId) => {
return fetch("http://localhost:3000/shifts", {
method: "GET",
headers: {
"Accept": "application/json",
"Content-Type": "application/json",
"Authorization": sessionId
}
});
};
callbackSessionId = (sessionId) => {
let promise1 = this.fetchUserAttributes(sessionId)
.then(response => response.json())
.then(json => this.setState({
userAttributes: json
}));
Promise.all([promise1]).then(() => {
let promise2 = this.getOrganisations(sessionId)
.then(response => response.json())
.then(json => this.setState({
organisations: json
}));
let promise3 = this.getShifts(sessionId)
.then(response => response.json())
.then(json => this.setState({
shifts: json
}));
// this.setState({
// sessionId: sessionId
// });
Promise.all([promise2, promise3]).then(() => {
this.setState({
sessionId: sessionId
});
});
});
};
Your JSON is actually invalid. All keys need to be string literals, so your correct JSON would look like this:
[
{
"id": 1,
"userId": 1,
"start": "2018-01-01 10:15",
"finish": "2018-01-01 12:20",
"breakLength": 30
},
{
"id": 2,
"userId": 1,
"start": "2018-01-02 10:15",
"finish": "2018-01-02 18:20",
"breakLength": 45
}
]
There are a few issues in your code: you should always return your promises, headers property names should be quoted and React setState is an asynchronous method.
Please, try to update it like below to see if it works, I'll edit expanding on the details if it does.
getShifts = (sessionId) => {
return fetch("http://localhost:3000/shifts", {
method: "GET",
headers: {
"Accept": "application/json",
"Content-Type": "application/json",
"Authorization": sessionId
}
});
};
fetchData = (sessionId) => {
let promise3 = this.getShifts(this.state.sessionId)
.then(response => response.json())
.then(json => this.setState({shifts: json}, this.forceUpdate));
};
I'm trying to make a simple dropdown list which data is gained from a fetch return..
if I use console to view the return, it shows like this :
[
{
"ID": "BOGOR~10"
"Location": "BOGOR"
},
{
"ID": "JADETABEK~16"
"Location": "JADETABEK"
}
]
if I want to take the location BOGOR and JADETABEK and put them into a Dropdown, how can I do that? this is my testing class
import React , { Component } from 'react';
import { View , StyleSheet , Text , Dimensions } from 'react-native';
import { Dropdown } from 'react-native-material-dropdown';
const ScreenWidth = Dimensions.get('window').width;
const Screenheight = Dimensions.get('window').height;
export default class testing extends Component {
constructor(props) {
super(props)
this.state = {
data: []
}
}
componentDidMount() {
fetch(url , {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({"lokasi":
{
}
})
})
.then(response => response.json())
.then(res => {
this.setState({
data: res.PilihLokasiResult.Lokasi
})
alert(res.PilihLokasiResult.Lokasi)
})
}
render() {
return(
<View style={styles.container}>
<View>
<Text>{this.state.location}</Text>
<Dropdown label="select location" style={{width: 400 }}/>
</View>
</View>
)
}
}
You need to format the data since react-native-material-dropdown accepts data in the form of {value: 'Sample'}
this.state = {
data: [],
dropDownData: []
}
const formatData = (data) => {
return data.map(dataObj => {
return {value: dataObj.Location} // return based on location
})
}
.then(res => {
const dropDownData = formatData(res.PilihLokasiResult.Lokasi)
this.setState({
data: res.PilihLokasiResult.Lokasi,
dropDownData
})
})
<Dropdown label="select location" data={this.state.dropDownData} style={{width: 400 }}/>