Reputation: 21
So I am building an app that I want to implement basically a 'like' button on and I can't seem to get the right combination of things to make it work. Basically I want to press a like button and have a number on the page that shows how many times it has been liked. Anyone have any ideas? This is what I have so far:
import React from 'react';
import { StyleSheet,View, Image,TouchableOpacity,Text, StatusBar,
ScrollView } from 'react-native';
export default class SingleVeg extends React.Component {
constructor(props){
super(props)
console.log("Here", props);
this.state = {
data: {},
count: 0
}
this.update = this.update.bind(this)
}
update() {
this.setState({ count: this.state.data.count + 1 })
}
async componentDidMount() {
const response = await fetch(`https://just-
ripe.herokuapp.com/vegetable/$
{this.props.navigation.state.params.id}`)
const json = await response.json()
this.setState({data: json})
}
render(){
console.log(typeof this.state.data, this.state.data.id)
return (
<View style={styles.container}>
<View style={styles.image}>
<Image
style ={{ width: 350, height: 200
}}
source={require("../../images/JustRipe.png")}/>
</View>
<Text style={styles.title}>{this.state.data.title}</Text>
<TouchableOpacity style={styles.love} onPress ={this.update}>
<Text style= {styles.loveText}>Love: {this.state.data.count}</Text>
</TouchableOpacity>
Upvotes: 0
Views: 8313
Reputation: 82
import React from 'react'`enter code here`;
class Counter extends React.Component {
state = { count: 0 }
increment = () => {
this.setState({
count: this.state.count + 1
});
}
decrement = () => {
this.setState({
count: this.state.count - 1
});
}
render() {
return (
<div>
<h2>Counter</h2>
<div>
<button onClick={this.decrement}>-</button>
<span>{this.state.count}</span>
<button onClick={this.increment}>+</button>
</div>
</div>
)
}
}
export default Counter;
Upvotes: 0
Reputation: 1527
You have a bug in your update function, it should be:
update() {
this.setState({ count: this.state.count + 1 })
}
vs. this.state.data.count
You should also update your text to read from count. ie.
Love: {this.state.count}
and when you save state:
this.setState({data: json, count: json.count})
Upvotes: 1
Reputation: 6171
The problem here is you have 2 count
storage.
Remove count
in state:
this.state = {
data: {},
count: 0
}
And update correct count in data:
this.setState({ data: { ...data, count: this.state.data.count + 1 }})
Upvotes: 1