i want to display the data as line graph instead of text.
i used react-native-charts-wrapper for graph please help me out
.then(res => res.json())
.then(res => {
console.log(`res: ${JSON.stringify(res['activities-distance'])}`);
this.setState({
result:res['activities-distance']});
})
}
render() {
return (
<View style={styles.container}>
<Text style={styles.welcome}>All-Day Activity</Text>
<Button title="CHECK STEPS" onPress{()=>this.connectFitbit()}/>
<FlatList
data={this.state.result}
renderItem={
({item}) => <View>
<Text>DATE : {item.dateTime}</Text>
<Text>STEPS :{item.value}</Text>
</View>
}
keyExtractor={(item, index) => {return index+item}}/>
</View>
Related
I'm working on an application in React Native to experiment with this and I made a bee in Django to retrieve data and send data.
For example, how can I send my data from an input text via a post to django?
For example for get I use something like this
const [todos, setTodos] = useState({});
const todoData = () => {
axios.get('http://192.168.1.5:8000/app/todo-data/')
.then(response => setTodos(response.data))
.catch(error => {
console.error('There was an error!', error);
});
};
React.useEffect(() => {
todoData();
}, []);
My question is how could I put in a "state" what data I want to send?
In Django I want to send this
{
"item":"how to make"
}
I want to send an item with a text as a post
And this is my TextInput
<View style={styles.container}>
<Header />
<View style={styles.header}>
<View style={styles.content}>
<View style={styles.list}>
<TextInput style={styles.textInput} editable maxLength={40}/>
<FlatList data={todos} renderItem={({ item }) => (
<TodoItem item={item} pressHandler={pressHandler} />
)}>
</FlatList>
</View>
</View>
</View>
</View>
To get input value to state you can use TextInput onChange callback.
https://reactnative.dev/docs/textinput#onchange
const [inputValue, setInputValue] = useState(null)
<TextInput
value={inputValue}
onChange={(val) => setInputValue(val)}
/>
Then you can include inputValue in POST request.
I use this to collect data from my server
getPopularProduct = async () => {
const url = `https://swissmade.direct/wp-json/swissmade/home/popular`;
fetch(url)
.then(response => response.json())
.then((responseJson) => {
console.log(responseJson.products.thumbnail, "details")
if(responseJson.error == false){
this.setState({
dataSourcePopularProduct: responseJson.products,
//isLoading: false,
})
}
})
.catch((error) => {
console.log(error)
})
}
this the blank space imag and this is the flat list and render item
renderPopularProduct = ({ item }) => {
const entities = new Entities();
var id = item.pid;
var img = { 'uri': item.thumbnail };
return (
<TouchableOpacity onPress={() => this.props.navigation.navigate('ProductDetails', { id })}>
<View style={styles.GalleryBox}>
<View style={styles.GalleryImg} onPress={() => this.props.navigation.navigate("ProductDetails")}>
<Image source={img} style={styles.SingelImg} largeHeap="true"/>
</View>
<View style={styles.GalleryText}>
<Text style={styles.userNmae}>{item.title}</Text>
</View>
<View style={styles.amount}>
<Text style={styles.userNmae}>{entities.decode(item.currency)} {item.price}</Text>
</View>
</View>
</TouchableOpacity>
)
}
<FlatList
data={this.state.dataSourcePopularProduct}
renderItem={this.renderPopularProduct}
keyExtractor={(item, index) => index}
horizontal={true}
showsHorizontalScrollIndicator={false}
/>
and stylesheet
SingelImg: {
width: '150%',
height: '120%',
//resizeMode: 'cover',
marginLeft: -25
},
And this way I use flat list but when it shows some data are missing especially image. but my API returns every right data.
I have a request pulling in from YouTube, to create a list of videos I want to display in a flatlist. I use the same approach across the application (calling WordPress, etc...), but when Im trying to achieve the same with the YouTube API (I've got the key setup etc..), it throws an error;
const Watch = ({typeOfProfile}) => {
const [isLoading, setLoading] = useState(true);
const [data, setData] = useState([]);
let x = {foo: 11, bar: 42};
function playertype(val) {
return 'https://www.googleapis.com/youtube/v3/searchpart=snippet&channelId=UCa_6KiOjxm6dEC_mMRP5lGA&maxResults=20&order=date&type=video&key=xxxxx';
}
useEffect(() => {
fetch(playertype(typeOfProfile))
.then((response) => response.json())
.then((json) => {
x = setData(json)
})
.catch((error) => console.error(error))
.finally(() => setLoading(false));
}, []);
const result = Object.keys(x).map(key => ({[key]: x[key]}));
return (
<View style={styles.body}>
<View style={styles.topscroll}>
{isLoading ? <ActivityIndicator/> : (
<FlatList
data={result}
horizontal={true}
keyExtractor={({ id }, index) => id}
renderItem={({ item }) => (
<View>
<Text>
{x.val}
</Text>
</View>
)}
/>
)}
</View>
</View>
);
};
Someone mentioned it could be an object being returned instead of an array, seems odd the json structure is the same as other requests I use this approach for.
I discovered that I had to add brackets on the data property of the FlatList. So instead of
data={data}
I had to change it too;
data={[data]}
Code now;
<FlatList
data={[data]}
horizontal={true}
keyExtractor={({ id }, index) => id}
renderItem={({ item, index }) => (
<View style={styles.container}>
<Image style={styles.imgyoutubeprev} source={{ uri: chkValue(item.items[0].snippet.thumbnails.high.url) }} />
</View>
)}
/>
I want to delete item from the FlatList. However, the solution from here is not working for my code. When I run my code, I am getting error such as 'index is not defined'.
I have yet to find other post regarding this issue so any help would be greatly appreciated.
Code snippet provided below:
export default class FrCreateScreen extends Component {
constructor(props) {
super(props);
this.state = {
//new timeSlots
timeSlots: [],
}
}
setEndTime = (event, appointmentEndTime, textEndTime) => {
appointmentEndTime = appointmentEndTime || this.state.appointmentEndTime;
textEndTime = textEndTime || moment(appointmentEndTime).format('h:mm a').toString();
this.setState({
showEndTime: Platform.OS === 'ios' ? true : false,
appointmentEndTime,
textEndTime,
timeSlots: [
...this.state.timeSlots,
{
apptdate: this.state.textAppointmentDate,
appttime: this.state.textAppointmentTime,
endTime: textEndTime,
}
],
});
}
deleteDateTime = (id) => {
const filteredData = this.state.timeSlots.filter(item => item.id !== id);
this.setState({ timeSlots: filteredData });
}
render() {
return (
<ScrollView>
...
<View>
<FlatList
data={this.state.timeSlots}
keyExtractor={({ id }, index) => index.toString()}
renderItem={({ item }) => {
return (
<View style={styles.containerList}>
...
<TouchableOpacity onPress={() => this.deleteDateTime(index)}>
<Feather name="trash" style={styles.icon} />
</TouchableOpacity>
</View>
</View>
);
}}
/>
</View>
</ScrollView>
)
};
};
Screenshot below:
I think you need to add index inside renderItem { item, index }
renderItem = {({ item, index }) => {
return (
<View style={styles.containerList}>
<TouchableOpacity onPress={() => this.deleteDateTime(index)}>
<Feather name="trash" style={styles.icon} />
</TouchableOpacity>
</View>
);
}}
While rendering in map function , it provides the index too, so try adding that.
renderItem={({ item,index }) => {
return (
<View style={styles.containerList}>
...
<TouchableOpacity onPress={() => this.deleteDateTime(index)}>
<Feather name="trash" style={styles.icon} />
</TouchableOpacity>
</View>
</View>
);
}}
Hope it helps
ok fixed. on touchable onPress, the argument should be 'item.index' instead of 'index'.
here's the correct code:
renderItem={({ item,index }) => {
return (
<View style={styles.containerList}>
...
<TouchableOpacity onPress={() => this.deleteDateTime(item.index)}>
<Feather name="trash" style={styles.icon} />
</TouchableOpacity>
</View>
</View>
);
}}
I have the following code:
export default class HomeScreen extends Component {
state = {text: ''};
_onPressSearch() {
Alert.alert("Button pressed!")
}
function getCitiesListFromApiAsync() {
return fetch("https://samples.openweathermap.org/data/2.5/find?lat=55.5&lon=37.5&cnt=10&appid=b6907d289e10d714a6e88b30761fae22.json")
.then((response) => response.json())
.then((responseJson) => {
return responseJson.list;
})
.catch((error) => {
Alert.alert("Error while loading: " + error);
})
}
render() {
return (<View style={styles.container}>
<ScrollView style={styles.scrollViewContainer} contentContainerStyle={styles.contentContainer}>
<View style={styles.searchContainer}>
<TextInput placeHolder="Type something!" onChangeText={(text) => this.setState({text})}
value={this.state.text}/>
</View>
<TouchableOpacity
onPress={this._onPressSearch}>
<View>
<Text>Search</Text>
</View>
</TouchableOpacity>
<View style={styles.container}>
<FlatList
data={this.getCitiesListFromApiAsync()}
renderItem={({item}) => <Text style={styles.item}>{item.name}</Text>}
/>
</View>
</ScrollView>
</View>);
}
}
Now I am trying to get data from server, parse it and add it to flatlist. I get data from this API: https://samples.openweathermap.org/data/2.5/find?lat=55.5&lon=37.5&cnt=10&appid=b6907d289e10d714a6e88b30761fae22.json. I created a special function for it, the same as in tutorial. But my IDE (Webstorm) marks it in red and writes that there should be a newline or semicolon after function name and when I run the app I have the following error:
Failed building JavaScript bundle.
SyntaxError: /Users/siarhei.mikhaylouski/WebstormProjects/WeatherApp/screens/HomeScreen.js: Unexpected token (23:13)
function getCitiesListFromApiAsync() {
| ^
24 | return fetch("https://samples.openweathermap.org/data/2.5/find?lat=55.5&lon=37.5&cnt=10&appid=b6907d289e10d714a6e88b30761fae22.json")
25 | .then((response) => response.json())
26 | .then((responseJson) => {
What's the matter and how can I solve it?
You should not use the function keyword when you define a method inside a class.
Just write:
getCitiesListFromApiAsync() {
// [...]
}