Getting error while trying to setState
in React Native.
Code
JavaScript
x
47
47
1
import React from "react";
2
import { TextInput, Text, View, Button, Alert } from "react-native";
3
4
const UselessTextInput = () => {
5
state = { currentDate: "" };
6
7
const setCurentDate = (val) => {
8
this.setState({currentDate : val});
9
};
10
11
const [value, onChangeText] = React.useState("");
12
13
return (
14
<View>
15
<Text
16
style={{
17
alignSelf: "center",
18
marginTop: 60,
19
fontWeight: "bold",
20
fontSize: "25",
21
}}
22
>
23
BirthReminder
24
</Text>
25
<Text style={{ alignSelf: "center", marginTop: 15, fontSize: 15 }}>
26
Enter your friend's birthdate, please
27
</Text>
28
<TextInput
29
clearTextOnFocus={true}
30
style={{
31
height: 40,
32
borderColor: "gray",
33
borderWidth: 1,
34
marginTop: 20,
35
width: 250,
36
alignSelf: "center",
37
}}
38
onChangeText={(value) => setCurentDate(value)}
39
value={value}
40
/>
41
<Button title="Add to list"></Button>
42
</View>
43
);
44
};
45
46
export default UselessTextInput;
47
Error
TypeError: undefined is not an object (evaluating ‘_this.setState’)
Advertisement
Answer
useState Hook
Functional components don’t have access to setState
method but useState hook.
useState hook works by defining the name of value, e.g. foo
followed by it’s setter. It’s a convention to name the setter with the same name as that of value with set prefix, i.e. setFoo
JavaScript
1
3
1
const [foo, setFoo] = useState('hi');
2
// pass the initial value here -^^-
3
Solution
JavaScript
1
10
10
1
import { useState } from 'react';
2
import { TextInput } from 'react-native';
3
4
const Component = () => {
5
const [value, setValue] = useState('');
6
7
return <TextInput value={value} onChangeText={setValue} />;
8
};
9
10