React-Native _this5.setState is not a function when changing the text in TextInput? - react-native

I am currently learning React-Native so apologies if the answer has appeared else where. But in my app whenever I change the text in the TextInput the program will crash with the error _this5.setState is not a function
i.e. if I search for 'Hello', everything works fine. But the moment when I change 'Hello' to 'Hell' the program crashes with that error.
Here's my code
export default class App extends React.Component {
constructor(props){
super(props)
this.state = {
apiKey: 'insertMyAPIKey',
isLoading: true,
text: ''
}
this.setInputState = this.setInputState.bind(this)
}
render() {
return (
<View style={{padding: 10}}>
<TextInput
style={{height: 40}}
placeholder="Search For Summoner!"
value={this.state.text}
onChangeText={(text) => this.setState({
text: text
})}
clearButtonMode="while-editing"
/>
<Button
onPress={() => {
this.MyFunctionsToRun(this.state.text)
}}
title="Search"
color="#841584"
/>
<Text style={{padding: 10, fontSize: 20}}>
Searching for summoner: {this.state.text}
</Text>
<Text>
The summoner ID: {this.state.summonerID}
</Text>
<Text>
The summoner Rank: {this.state.leagueName}, {this.state.tier} {this.state.rank}, {this.state.leaguePoints}
</Text>
<Text>
The Summoner Win Rate: {this.state.winRate}
</Text>
<View>
<FlatList
data={this.state.lastTenGames}
renderItem={({item}) => <Text>{item.lane}</Text>}
/>
</View>
</View>
);
}
}

you can try this
onChangeText={text => (this.state.text = text)}
or use another function
onChangeText={this.changeText}
changeText = text => {
this.setState({text: text});
};
i hope it works for you :D

Related

TouchOpacity onPress request is not working with formik and react-native-text-input-mask

When i tried to login the button is not sending request. On button pree i supposed to console the output. It seems that the onChangeText and onChange is not working correcttly in TextInputMask.
TouchableOpacity tag has onPress event where onPress={()=>formikProps.handleSubmit()} is not triggering the onSubmit props of formik.
Here i'm using yup for validation and Formik for submitting data.
const validationSchema = yup.object().shape({
phoneNumber: yup
.string()
.label("Phone Number")
.required("Phone Number is required."),
password: yup.string().label("Password").required("Password is required."),
});
class Home extends Component {
constructor(props) {
super(props);
this.state = {
username: "",
password: "",
press: false,
ButtonStateHolder: false,
};
}
render() {
return (
<ImageBackground style={{ width: "100%", height: "100%" }} source={bgImg}>
<ScrollView>
<Formik
initialValues={{ phoneNumber: "", password: "" }}
onSubmit={(values, actions) => {
this.setState({
password: values.password,
ButtonStateHolder: true,
});
console.warn(this.state.phoneNumber);
console.warn(this.state.password);
}}
validationSchema={validationSchema}
>
{(formikProps) => (
<React.Fragment>
<View>
<View>
<Text>Phone number</Text>
<TextInputMask
keyboardType="number-pad"
ref={(ref) => (this.phoneField = ref)}
onChangeText={(formatted, extracted) => {
this.setState({
phoneNumber: extracted,
});
}}
onChange={formikProps.handleChange("phoneNumber")}
onBlur={formikProps.handleBlur("phoneNumber")}
placeholder={""}
mask={"([000]) [000] [0000]"}
/>
<Text style={styles.errMsg}>
{formikProps.touched.phoneNumber &&
formikProps.errors.phoneNumber}
</Text>
</View>
<View>
<Text style={styles.formLable}>Password</Text>
<TextInput
onChangeText={formikProps.handleChange("password")}
onBlur={formikProps.handleBlur("password")}
placeholder={""}
returnKeyType={"done"}
autoCapitalize={"none"}
autoCorrect={false}
/>
<Text style={styles.errMsg}>
{formikProps.touched.password &&
formikProps.errors.password}
</Text>
<TouchableOpacity
activeOpacity={0.7}
style={styles.btnEye}
onPress={this.showPass}
>
<Image source={eyeImg} style={styles.iconEye} />
</TouchableOpacity>
</View>
</View>
<View style={styles.loginBottom}>
<TouchableOpacity
style={styles.button}
onPress={() => formikProps.handleSubmit()}
>
<Text style={styles.buttonText}> Login </Text>
</TouchableOpacity>
</View>
</React.Fragment>
)}
</Formik>
</ScrollView>
</ImageBackground>
);
}
}
export default Home;
onPress console log is not printed
Someone please help to solve this issue
Formik will manage the state of inputs for you so you don't need to declare it.
const validationSchema = yup.object().shape({
phoneNumber: yup
.string()
.label("Phone Number")
.required("Phone Number is required."),
password: yup.string().label("Password").required("Password is required."),
});
class Home extends React.Component {
constructor(props) {
super(props);
}
render() {
return (
<View>
<ScrollView>
<Formik
initialValues={{ phoneNumber: "", password: "" }}
onSubmit={(values, actions) => {
alert(JSON.stringify(values));
}}
validationSchema={validationSchema}
>
{({handleChange, values, handleSubmit, touched, errors, handleBlur}) => (
<React.Fragment>
<View>
<View>
<Text>Phone number</Text>
<TextInput
keyboardType="number-pad"
onChangeText={handleChange}
onChange={handleChange("phoneNumber")}
onBlur={handleBlur("phoneNumber")}
placeholder={""}
mask={"([000]) [000] [0000]"}
value={values.phoneNumber}
/>
<Text>
{touched.phoneNumber &&
errors.phoneNumber}
</Text>
</View>
<View>
<Text>Password</Text>
<TextInput
onChangeText={handleChange("password")}
onBlur={handleBlur("password")}
placeholder={""}
returnKeyType={"done"}
autoCapitalize={"none"}
autoCorrect={false}
value={values.password}
/>
<Text>
{touched.password &&
errors.password}
</Text>
</View>
</View>
<View >
<TouchableOpacity
onPress={() => handleSubmit()}
>
<Text> Login </Text>
</TouchableOpacity>
</View>
</React.Fragment>
)}
</Formik>
</ScrollView>
</View>
);
}
}
You can also manage the form with the useFormik hook instead of the Formik component
import { useFormik } from 'formik';
const validationSchema = yup.object().shape({
phoneNumber: yup
.string()
.label("Phone Number")
.required("Phone Number is required."),
password: yup.string().label("Password").required("Password is required."),
});
const Home = () => {
const { handleChange, values, handleSubmit, touched, errors, handleBlur } = useFormik({
initialValues: {
phoneNumber: "", password: ""
},
onSubmit: (values, actions) => {
alert(JSON.stringify(values));
},
validationSchema
});
console.log(values);
return (
<View>
<ScrollView>
<View>
<View>
<Text>Phone number</Text>
<TextInput
keyboardType="number-pad"
onChangeText={handleChange}
onChange={handleChange("phoneNumber")}
onBlur={handleBlur("phoneNumber")}
placeholder={""}
mask={"([000]) [000] [0000]"}
value={values.phoneNumber}
/>
<Text>
{touched.phoneNumber &&
errors.phoneNumber}
</Text>
</View>
<View>
<Text>Password</Text>
<TextInput
onChangeText={handleChange("password")}
onBlur={handleBlur("password")}
placeholder={""}
returnKeyType={"done"}
autoCapitalize={"none"}
autoCorrect={false}
value={values.password}
/>
<Text>
{touched.password &&
errors.password}
</Text>
</View>
</View>
<View >
<TouchableOpacity
onPress={() => handleSubmit()}
>
<Text> Login </Text>
</TouchableOpacity>
</View>
</ScrollView>
</View>
);
}
}
Let me know if I misunderstood something or if it helps you

Unable to navigate from one screen to another

I am not able to navigate from one screen to another, I don't know why can anyone tell me what is the proper solution of this Error.
export default class Pro extends React.Component {
constructor(props) {
super(props);
this.state = {
email: '',
username: '',
};
}
_onPressButton = () =>{
this.props.navigation.navigate('Profile');
}
render() {
return (
<Block row style={styles.main}>
<Block>
<Image
source={{ uri: Images.ProfilePicture }}
style={styles.avatar}
/>
</Block>
<Block center>
<TouchableOpacity onPress={this._onPressButton()} underlayColor="white">
<Text>User name</Text>
<Text>Email</Text>
</TouchableOpacity>
</Block>
</Block>
);
}
}
Any help will be appreciated.
Use your button TouchableOpacity like this :
<TouchableOpacity onPress={() => this._onPressButton()} underlayColor="white">
<Text>User name</Text>
<Text>Email</Text>
</TouchableOpacity>
<TouchableOpacity onPress={() => {this._onPressButton}} underlayColor="white">
<Text>User name</Text>
<Text>Email</Text>
</TouchableOpacity>
You might also try this
Check the route page, because you may forget to add routes.
Profile: {
screen: ProfileView,
navigationOptions: {
header: null,
}
}

“How to fix ‘handlePress’ error in react-native”

Below is my login class code :
export default class Login extends Component {
constructor(props) {
super(props);
this.state = {
loggedIn: true,
}
handlePress = () => {
this.props.onHomeviewPress(this.state.data);
}
}
render() {
return (
<View style={styles.container}>
<Text style={{ color: "blue", fontSize: 28, marginLeft: 10 }}> Login</Text>
<TextInput style={styles.input}
underlineColorAndroid="transparent"
placeholder="Email"
placeholderTextColor="blue"
autoCapitalize="none"
/>
<TextInput style={styles.input}
underlineColorAndroid="transparent"
placeholder="Password"
placeholderTextColor="blue"
autoCapitalize="none"
/>
<Button
onPress={() => this.handlePress.bind(this)}
title="Login"
/>
</View>
);
}
}
HAVING PROBLEM IN HANDLEPRESS FUNCTION IS NOT WORKING GIVING ERROR
undefined is not an object('_this2.handlepress.bind')
Please Help me solve this. Thanks in advance
Your handlePress function is defined in your constructor.
Move it outside and it will work
Also, you don't need to bind the function. Just onPress={this.handlePress} will work.

Change TextInput editable attribute when I press a button (Not working)

I am trying to change editable with state with the click of a button, but it is not working for some reason. I have seen other people do it this way and it works. Is there another way to do this instead? or am i missing something? Thanks
`class Settings extends Component {
constructor(props) {
super(props);
this.state = {
editable: false,
name: '',
};
this.handleEdit = this.handleEdit.bind(this);
this.handleName = this.handleName.bind(this);
}
handleEdit() {
this.setState({
editable: !this.state.editable,
});
}
handleName = (text) => {
this.setState({
name: text,
});
};
render() {
return(
<View style={styles.container}>
<View style={styles.headerContainer}>
<Text style={styles.header}>Settings</Text>
</View>
<View style={styles.section}>
<View style={styles.sectionTitleContainer}>
<Text style={styles.sectionTitle}>My Account</Text>
</View>
<View>
<Text>Name:</Text>
<TextInput
placeholder="name"
value={this.state.name}
onChangeText={this.handleName}
editable={this.state.editable}
/>
</View>
<View>
<TouchableOpacity onPress={() => this.handleEdit}>
<Text>Edit</Text>
</TouchableOpacity>
</View>
</View>
</View>
);
}
}
export default Settings;`
Change your
<TouchableOpacity onPress={() => this.handleEdit}>
To
<TouchableOpacity onPress={this.handleEdit}>
I believe that since you already binded 'this' to the handleEdit function you dont need to pass the () => anymore.

state disappears when method is call

I'm working on a class project and my state is disappearing. After componentDidMount console.log(this.state) is fine. I initiate setInterval and call inc(). Somehow when I enter inc() the state gets wiped out.
import React from 'react';
import { TextInput,Button,StyleSheet, Text, View } from 'react-native';
import styles from './styles/styles.js';
debug=true
export default class App extends React.Component {
constructor(){
super()
this.state={timer:'WORK',
workTime: 25*60+0,
breakTime: 5*60+0,
currentTime:0,
remainingTime:null,
min:0,
sec:0,
startFlag:false,
resetFlag:false}
}
componentDidMount(){
this.interval=setInterval(this.inc,10000)
if(debug)console.log('COMPONENTDIDMOUNT',this.state)
}
static getDerivedStateFromProps(nextProps, prevState) {
if(debug)console.log('GETDERIVEDSTATEFROMPROPS',prevState)
return null
}
shouldComponentUpdate(nextProps,nextState){
if(debug)console.log('SHOULDCOMPONENTUPDATE',nextState)
return true
}
componentDidUpdate(){
if(debug)console.log('COMPONENTDIDUPDATE',this.state)
}
componentWillUnmount(){
if(debug)console.log('COMMPONENTWILLUNMOUNT',this.state)
}
startToggle(){
if(endTime === null)this.setState({remainingTime:this.state.workTime,
startFlag:!this.state.startToggle})
else this.setState({remainingTime:!this.state.startFlag})
}
textTime(){
let min = Math.floor(this.state.remainingTime / 60).toString()
let sec = (this.state.remainingTime % 60)
if (sec < 10)sec ? '0' + sec : sec.toString()
this.setState({min:min,sec:sec})
}
inc(){
console.log(this.state)
}
captureInput(){}
render() {
console.log('RENDER',this.state)
return (
<View style={styles.container}>
<Text style={styles.bigFont}>{`${this.state.timer + 'TIMER'}`}</Text>
<Text style={styles.bigFont}>12:00</Text>
<View style={styles.button}>
<Button title='START' onPress={()=>this.startToggle()} />
<Button title='RESET' onPress={()=>this.resetToggle()} />
</View>
<View style={styles.row}>
<Text style={[styles.bold,{marginRight:10},{width:112},
{textAlign:'right'}]}>
'Work Timer:'</Text>
<Text style={styles.bold}> min:</Text>
<TextInput
defaultValue='50'
style={styles.input}
onChangeText={(text) => {this.captureInput(text)}}
/>
<Text style={styles.bold}> sec:</Text>
<TextInput
defaultValue='50'
style={styles.input}
onChangeText={(text) => {this.captureInput(text)}}
/>
</View>
<View style={styles.row}>
<Text style={[styles.bold,{marginRight:10},{width:112},
{textAlign:'right'}]}>
'Break Timer:'</Text>
<Text style={styles.bold}> min:</Text>
<TextInput
defaultValue='50'
style={styles.input}
onChangeText={(text) => {this.captureInput(text)}}
/>
<Text style={styles.bold}> sec:</Text>
<TextInput
defaultValue='50'
style={styles.input}
onChangeText={(text) => {this.captureInput(text)}}
/>
</View>
</View>
)
}
}
You have 2 options:
Change inc() to inc = () =>
or
Change this.inc to this.inc.bind(this)
Change your inc method declaration to
inc = () => {
...
}
As per your code, this inside inc() is not referring to the component, hence you are not getting state either.
Hope this will help!