Reputation: 452
I can see there's a lot of similar questions, but none of the answer could help me.
I get this error when running the code below: TypeError: undefined is not an object (evaluating 'this.state') I also get this error, but this is connected to this.setState(): TypeError: _this.setState is not a function. (In '_this.setState({ checked: !_this.state.checked })', '_this.setState' is undefined)
<CheckBox
center
title='Click Here'
checked={this.state.checked}
onPress={() => this.setState({checked: !this.state.checked})}
/>
The whole code (if necessary):
export default function NewEventScreen() {
const [date, setDate] = useState(new Date());
const [mode, setMode] = useState('date');
const [show, setShow] = useState(false);
const onChange = (event, selectedDate) => {
const currentDate = selectedDate || date;
setShow(Platform.OS === 'ios');
setDate(currentDate);
};
const showMode = (currentMode) => {
setShow(true);
setMode(currentMode);
};
const showDatepicker = () => {
showMode('date');
};
const showTimepicker = () => {
showMode('time');
};
handleEventCreation = () => {
const { title, description } = this.state
firebase.firestore()
.collection('users').doc(firebase.auth().currentUser.uid).collection('events').doc().set({
title: title,
description: description,
}).then(() => { console.log("Document written")
this.setState({
title: '',
description: '',
})
}).catch(error => console.log(error))
}
state = {
title: '',
description: '',
checked: false,
}
onPress = () => {
this.setState({checked: !this.state.checked})
}
return (
<View style={styles.container}>
<Text style={styles.title}>Here can you make your events!</Text>
<TextInput
style={styles.inputBox}
value={state.title}
onChangeText={title => this.setState({ title })}
placeholder='Title'
/>
<TextInput
style={styles.inputBox}
value={state.description}
onChangeText={description => this.setState({ description })}
placeholder='Description'
/>
<CheckBox
center
title='Click Here'
checked={this.state.checked}
onPress={() => this.onPress()}
/>
<View>
<View>
<Button onPress={showDatepicker} title="Show date picker!" />
</View>
<View>
<Button onPress={showTimepicker} title="Show time picker!" />
</View>
{show && (
<DateTimePicker
testID="dateTimePicker"
value={date}
mode={mode}
is24Hour={true}
display="default"
onChange={onChange}
/>
)}
</View>
<TouchableOpacity style={styles.button} onPress={handleEventCreation}>
<Text style={styles.buttonText}>Create Event</Text>
</TouchableOpacity>
</View>
)
}
Upvotes: 1
Views: 2990
Reputation: 1571
You are using this.setState
inside a functional component. You cannot mix those two together (you can only use it inside a class component). If you want to use checked
you need to add const [checked, setChecked] = useState(false);
and use setChecked
to set state of checked. Same goes for title
and description
.
Upvotes: 1