React-Native: Display JSON Data - reactjs

function getData(access_token) {
fetch('https://api.fitbit.com/1/user/-/activities/steps/date/today/1m.json', {
method: 'GET',
headers: {
Authorization: `Bearer ${access_token}`,
},
// body: `root=auto&path=${Math.random()}`
})
.then(res => res.json())
.then(res => {
console.log(`res: ${JSON.stringify(res)}`);
})
.catch(err => {
console.error('Error: ', err);
});
}
export default class App extends Component {
connectFitbit = () => {
OAuth(client_id, getData);
};
render() {
return (
<View style={styles.container}>
<Text style={styles.welcome}>Welcome to Fitbit Integration</Text>
<Button title="connect fitbit" onPress={() => this.connectFitbit()} />
</View>
);
}
}
I'm trying to get fit bit steps JSON data in react native app ,
right now I am getting the output in console ,now i want to parse the step data in my app please help me out

If you want to display your data in to flatlist...
First you need to make array for saving your response data..
constructor(props) {
super(props);
this.state = {
...
result: [],
...
};
}
function getData(access_token) {
fetch('https://api.fitbit.com/1/user/-/activities/steps/date/today/1m.json', {
method: 'GET',
headers: {
Authorization: `Bearer ${access_token}`,
},
})
.then(res => res.json())
.then(res => {
console.log(`res: ${JSON.stringify(res)}`);
// if your response have anu json array
this.setState({
result:res.data,
});
})
.catch(err => {
console.error('Error: ', err);
});
}
After, in flatlist simply set this array,
<FlatList
data={this.state.result}
renderItem={item => your render view}
keyExtractor={(item, index) => your key item}/>

Related

Method called on render without click react native

I am having an issue where a method is being called automatically on render in my react native application. Here are the snippets:
static navigationOptions = ({navigation}) => {
return {
headerTitle: 'Network',
headerRight: () => (
<View style={{flexDirection: 'row'}}>
<Button
title='Invite'
color='#ccc'
onPress={() => navigation.navigate('InviteUser')}
/>
<Button
title='Search'
color='#ccc'
onPress={() => navigation.state.params.handleSearch}
/>
</View>
),
};
};
componentDidMount() {
this.state = {
dataSource:[],
};
this.props.navigation.setParams({ handleSearch: this.getNearbyUsers(user_id, auth_token)})
}
It's happening specifically for the search button. Invite works fine. I am pretty new to RN still, so can anyone give some help please?
Edit* added getNearbyUser():
getNearbyUsers(user_id, auth_token) {
console.log('Get Users: id:' + user_id);
let formData = new FormData();
formData.append('user_id', user_id);
formData.append('auth_token', auth_token);
fetch("https://{url}", {
method: 'POST',
header: {
Accept: 'application/json',
'Content-Type': 'multipart/form-data'
},
body: formData
//JSON.stringify({'user_id': user_id, 'auth_token': auth_token})//, 'latitude': 33.0296843, 'longitude': -96.7059628})
}).then(response => response.json())
.then((responseJson) => {
// console.log(responseJson.users[0])
this.createSearchList(responseJson.users)
}).catch((error) => {
console.log('Local Network Error: ' + error)
})
}
Change
this.props.navigation.setParams({ handleSearch: this.getNearbyUsers(user_id, auth_token)})
To
this.props.navigation.setParams({ handleSearch: () => this.getNearbyUsers(user_id, auth_token)})

show in react-alert fetch

I want to show a successful or failed alert after the update with fetch. I can show a message with the button, but no alert is shown in the fetch operation.
How to display alert in Fetch
show in react-alert fetch
I'm using the react-alert component.
https://www.npmjs.com/package/react-alert
async handleSubmitUpdate() {
await fetch(`${this.domain}/api/debt/update/`, {
method: "PUT",
headers: {
Authorization: `Bearer ${localStorage.getItem("token")}`,
"Content-Type": "application/json"
},
body: JSON.stringify({
user: this.props..id,
})
})
.then(response => {
return response.json();
})
.then(json => {
this.componentDidMount();
return (<AlertMessageBox type={"success"} data={"Update succesfully"} />)
})
.catch(err => console.log(err));
}
AlertMessageBox.js
import React from 'react';
import { useAlert } from 'react-alert';
const AlertMessageBox = ({ type, data }) => {
const alert = useAlert();
console.log(data);
const showAlert = () => {
switch (type) {
case 'error':
alert.error(<div style={{color: 'red'}}> data </div>);
return;
case 'show':
alert.show(<div style={{color: 'white'}}> data </div>);
return;
case 'info':
alert.success(<div style={{color: 'green'}}> data </div>);
return;
default:
return;
}
};
return <div> { showAlert() } Deneme</div>;
};
export default AlertMessageBox;
You should have a state variable for this.
state = {
showSuccessAlert: false,
showFailAlert: false
}
Then you can set state variable on success / failure,
await fetch(`${this.domain}/api/debt/update/`, {
method: "PUT",
headers: {
Authorization: `Bearer ${localStorage.getItem("token")}`,
"Content-Type": "application/json"
},
body: JSON.stringify({
user: this.props..id,
})
})
.then(response => {
return response.json();
})
.then(json => {
//this.componentDidMount(); //I don't think you can call this
//Change the state here which will show your Alert
this.setState({
showSuccessAlert: true
})
})
.catch(err => {
console.log(err);
//Change the state here which will show your Alert
this.setState({
showFailAlert: true
})
);
In your render method you should have your alert with condition,
render(){
return(
<div>
{ this.state.showSuccessAlert && <AlertMessageBox type={"success"} data={"Update succesfully"} /> }
{ this.state.showFailAlert && <AlertMessageBox type={"error"} data={"Data update failed"} /> }
....
</div>
)
}

How do I set get the specific array index of JSON response array to TextInput in React Native

I am able to fetch my complete response in react native the code is as follow to fetch the data
import React, { Component } from 'react';
import {
View,
Text,
TouchableOpacity,
FlatList,
} from 'react-native';
export default class App extends Component {
constructor(props) {
super(props);
this.state = {
dataSource: [],
}
}
componentDidMount() {
let content = '/LoginPageLoad_Arr';
const url = 'abc.asmx' + content;
fetch(url, {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json; charset=utf-8',
},
})
.then((response) => response.json())
.then((responseJson) => {
const result = JSON.parse(responseJson.d)
this.setState({
dataSource: result.Table1
})
}).catch((error) => {
console.error(error);
});
}
_renderItem = ({ item }) => (
<TouchableOpacity>
<View>
<Text>
{item.ID} = {item.VALUE}
</Text>
</View>
</TouchableOpacity>
)
render() {
return (
<View>
<FlatList
data={this.state.dataSource}
renderItem={this._renderItem}
// keyExtractor={(item, index) => index}
/>
</View>
)
}
}
My concern is to fetch the ID and VALUE at the index 0. I tried adding the code item.ID[0] it just fetch me the first letter of all the ID. I want complete complete ID at just index 0 to set in TextInput. Please if someone as worked on it help me out.
First, better method is to cut your function in ComponentDidMount, and use async instead of .then() like :
ComponentDidMount(){
this.callApiFunction();
}
async callApiFunction(){
try{
let content = '/LoginPageLoad_Arr';
const url = 'abc.asmx' + content;
const call = await fetch(url, {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json; charset=utf-8',
},
})
call = call.json();
call = JSON.parse(call.d)
//If you want to browse an array, you can use the map function
call.map((item, index) => {
//And make condition here, for exemple the first element
if(index == 0){
//DO what u want
console.log(item)
this.setState({
dataSource: item
})
}
})
}).catch((error) => {
console.error(error);
});
}
catch(e){
console.log(e)
}
}
Hope it will help you

How can I dynamically rerender my api to my webpage?

So I have this api and I am making a get request in my ComponentDidMount() to dynamically render it to my page and it works. The issue I am facing is when I make a post request to add items to the list, it does not show on my webpage unless I refresh it. The backend is my data.json so I don't know if that is the problem but essentially when I make a post request, I am adding data to my data.json and I want that to rerender on my page without me refreshing it.
componentDidMount() {
axios.get("/api/workboard")
.then(res => {
res.data["boardLists"].map((item, key) => {
// console.log(Object.keys(item)[0])
this.setState(prevState => ({
data: [...prevState.data, item],
titles: [...prevState.titles, Object.keys(item)[0]]
}))
})
// console.log(this.state.titles)
// console.log(this.state.data)
}).catch(err => console.log(err))
}
addListItemHandler = () => {
axios({
method: 'post',
url: 'api/workboard/0/list',
data: {
title: "Untitled" ,
description: "No Description"
}
})
.then(res => {
console.log(res)
})
.catch(err => console.log(err));
}
render() {
let board = this.state.data.map((item, key) => {
return <WorkBoardContainer
key={key}
title={item[this.state.titles[key]]["title"]}
listItems={item[this.state.titles[key]]["list"].map((i) => {
return i["title"]
})}
/>
})
return (
<div className={classes.App}>
<AddButton addListItemHandler={this.addListItemHandler}/>
{board}
</div>
);
}
Try moving the fetching part as a seperate function and call it again once the post request is done.
componentDidMount() {
// fetch data when component is mounted
this.fetchData();
}
fetchData = () => {
axios.get("/api/workboard")
.then(res => {
res.data["boardLists"].map((item, key) => {
this.setState(prevState => ({
data: [...prevState.data, item],
titles: [...prevState.titles, Object.keys(item)[0]]
}))
})
}).catch(err => console.log(err))
}
addListItemHandler = () => {
axios({
method: 'post',
url: 'api/workboard/0/list',
data: {
title: "Untitled" ,
description: "No Description"
}
})
.then(res => {
console.log(res);
// fetch data again once post is done.
this.fetchData();
})
.catch(err => console.log(err));
}

React API returns empty

fairly new to react but I have the following API data I want to create as a list or whatever:
https://jsonblob.com/53c7f296-d79d-11e8-839a-a312b719c60a
My react component looks like this:
class Contacts extends Component {
constructor(props) {
super(props)
this.state = {
contacts:[]
}
}
componentDidMount() {
fetch('https://api.billysbilling.com/v2/contacts?organizationId=kZeGqbBRSXyeeDoWNkF3jQ',{
headers: {
'X-Access-Token': API_KEY,
'Content-Type': 'application/json'
},
})
.then(response => {
return response.json();
})
.then(response => console.log(response))
.then(d => {
this.setState({ contacts: d });
console.log("state", this.state.contacts)
})
}
render() {
return (
<div>
{
this.state.contacts.map(((contact, index) =>
<th key={`${contact.contact}${index}`}>
<div>
<div>
{contact.contact}
</div>
</div>
</th>
))
}
</div>
);
}
But however it seems to return nothing.
The console.log actually shows the data, so I am pretty stuck.
It would be awesome if some of you could help.
The state also just returns an empty array in the react tools in chrome.
When you write then(response => console.log(response)), you are not returning anything, so d will be undefined in the function given to the following then.
You could write it like this instead:
fetch('https://api.billysbilling.com/v2/contacts?organizationId=kZeGqbBRSXyeeDoWNkF3jQ',{
headers: {
'X-Access-Token': API_KEY,
'Content-Type': 'application/json'
},
})
.then(response => {
return response.json();
})
.then(d => {
console.log(d);
this.setState({ contacts: d.contacts });
});

Resources