'undefined is not an object (evaluating 'props.deviceLocale') - android

I am trying to validate a text field on click of Submit button. But I always get the error -
TypeError: undefined is not an object (evaluating 'props.deviceLocale') on my emulator.
(I am using an Android emulator).
However I am nowhere using 'deviceLocale' in my code. I am not aware if it is required for anything I have in my code.
This is my code:
import React, {Component} from 'react';
import { View, Text, TouchableOpacity, TextInput } from 'react-native';
import ValidationComponent from 'react-native-form-validator';
export default class App extends ValidationComponent {
constructor() {
super()
this.state = {
name: "abc"
}
}
_onPressButton() {
this.validate({
name: {minlength: 3, maxlength: 7, required: true},
});
}
render() {
return (
<View>
<TextInput
ref = "name"
onChangeText = {(name) => this.setState({name})}
value = {this.state.name}
/>
<TouchableOpacity onPress = {this._onPressButton}>
<Text>Submit</Text>
</TouchableOpacity>
</View>
)
}
}
Error snap:

You are getting the error even before loading of the component then, do bind your _onPressButton correctly, then atleast your component will get mounted properly, then then your upcoming errors will follow like the use of this.validate is somewhat ambiguous to me as I cannot see validate function in the component.
To bind your _onPressed, declare it like below:
_onPressButton = () => {
this.validate({
name: {minlength: 3, maxlength: 7, required: true},
});
}
The error is causing as _onPressed is getting called as soon as your component is getting mounted. Let me know in comments if this helps you getting ahead with your component mounting atleast.
Edited:
Also, your constructor doesn't provide props to the super constructor,
Declare it like below:
constructor(props) {
super(props);
this.state = {
name: "abc"
}
}

Related

React Naive Colour Picker module errror

Please Help!!!
I Copy pasted code from https://www.npmjs.com/package/react-native-wheel-color-picker
In my App.js file but its not running
I installed on 3 library mentioned but it didn't work
Please help me to fix this code or I need a code of similar Colour wheel
(There is module Colour wheel similar to Colourpicker but it also didn't work for me)
import { Component } from 'react'
import { View, Text } from 'react-native'
import ColorPicker from 'react-native-wheel-color-picker'
class App extends Component {
render() {
return (
<View style={[]}>
<ColorPicker
ref={r => { this.picker = r }}
color={this.state.currentColor}
swatchesOnly={this.state.swatchesOnly}
onColorChange={this.onColorChange}
onColorChangeComplete={this.onColorChangeComplete}
thumbSize={40}
sliderSize={40}
noSnap={true}
row={false}
swatchesLast={this.state.swatchesLast}
swatches={this.state.swatchesEnabled}
discrete={this.state.disc}
/>
<SomeButton onPress={() => this.picker.revert()} />
</View>
)
}
}
export default App
Error I am getting
The error says null is not an object (evaluating 'this.state.currentColor')
The color prop on the ColorPicker component expects an object and is given null. This is because there is no state set. Using a class based component you can set the state in the constructor. This gets rid of the error. If you want you can define you "start" color in the state currentColor: "#cc7"
import { Component } from "react";
import { View } from "react-native";
import ColorPicker from "react-native-wheel-color-picker";
class App extends Component {
constructor(props) {
super(props);
this.state = {};
}
render() {
return (
<View style={[]}>
<ColorPicker
ref={(r) => {
this.picker = r;
}}
color={this.state.currentColor}
swatchesOnly={this.state.swatchesOnly}
onColorChange={this.onColorChange}
onColorChangeComplete={this.onColorChangeComplete}
thumbSize={40}
sliderSize={40}
noSnap={true}
row={false}
swatchesLast={this.state.swatchesLast}
swatches={this.state.swatchesEnabled}
discrete={this.state.disc}
/>
// SomeButton
</View>
);
}
}
export default App;
PS: the SomeButton component will also throw an error since it is not defined.

Syntax Error in React Native for Android Development

import { View, ScrollView, StyleSheet } from 'react-native'
import Heading from './Heading'
import Input from './Input'
class App extends Component {
constructor () {
super()
this.state = {
input value: '',
todos: [],
type: 'All'
}
inputChange (inputValue) {
this.setState({inputValue})
}
}
render () {
const {todos, inputValue, type } = this.state
return (
<View style={styles.container}>
<ScrollView keyboardShouldPersistTaps='always'
style={styles.content}>
<Heading />
<Input
input Value={inputValue}
inputChange={(text) => this.inputChange(text)} />
</ScrollView>
</View>
)
}
}
const styles = StyleSheet.create ({
container: {
flex: 1,
backgroundColor: '#f5f5f5'
},
content: {
flex: 1,
paddingTop: 60
}
})
export default App
"So I have this error that I have tried to fix through disabled eslint and it's not working. This is my first time using react-native. I'm taking a class and this is for an assignment of mine to create a TodoApp. My teacher gave us the exact code he wanted us to input into VSCode, so we could then make changes to it accordingly for the assignment. I was halfway through his video, and this error kept coming up, but not for him. I have looked all around for an answer and can't seem to find one. The section of code that gives me a problem in the inputChange (inputValue) and say it's missing a semicolon. In the video the teacher doesn't put one and it works completely fine. I've done some reading that it could be eslint, but I've tried to disable it and it still doesn't work."
With this code, you are attempting to define the method inputChange inside the constructor method, which is not possible. You need to close the constructor method definition before defining your inputChange method. I recommend taking a closer look at the code your instructor provided. I suspect that on closer inspection you will find one curly brace closing the setState function and another curly brace closing the constructor method before that inputChange method definition starts.
change position of inputChange function from inside of constructor to body of class ( after closing constructor )
class App extends Component {
constructor() {
// ...
}
inputChange(inputValue) {
// ...
}
render() {
return (
<>{/* rest of code */}</>
);
}
}
Edit
you may name properties incorrect

How to change value of input react native

Sorry I am new to React Native, and want to know how to change current input value?
As in my case, if I enter a new word directly into input the previous word or the previous value in the value will continue to appear without changing or replacing the new one.
class component:
Keep the value of the input in state of your component which holds this TextInput component.
class ParentComponent extends React.Component {
constructor (props) {
super(props)
this.state = { queryText: '' }
}
handleInputTextChange = (newText) => {
this.setState({ queryText: newText })
}
render () {
return (<View>
<TextInput
onChangeText={this.handleInputTextChange}
value={this.state.queryText}
/>
</View>)
}
}
Notice How I have used onChangeText and handleInputTextChange to handle new values.
Functional Component:
in the functional components, we use hooks. To hold and update text value we use useState
export default () => {
const [text, setText] = useState("");
return <TextView value={text} onChangeText={setText} />;
};
Hello you can use this method :
this.state = {
email: '13119165220',
}
onChangeText={text => this.setState({ email: text })}
In functional components use
export default () => {
const [text,setText] = React.useState("")
return <TextView
value={text}
onChangeText={setText} />
}
TextInput needs value that it is the value that is gonna be shown inside the TextInput.
And to update that value you use onChangeText that is gonna call whatever function you specify every time the text into the TextInput change.
Depending if you are learning React with hooks or without your code will change:
with hooks:
import React,{useState} from 'react'
//others import
function MyTextInput (props){
const [userInput,setUserInput] = useState()
return (
<TextInput
value = {userInput}
onTextChange = {(text) => setUserInput(text)} /> //is always better call another function
) // where you can validate the input
if your using class and coding without hooks, the logic is the same, just change the syntax:
import React,{Component} from 'react'
//other imports
class MyTextInput extends Component{
constructor(props){
super(props)
this.state = {
userInput:''
}
render(){
return (
<TextInput value = {this.state.userInput}
onChangeText = { text => this.setState({userInput:text}) />
)
}
}
Here the links for the docs, where you can find all the props that TextInput receive with explanation: https://reactnative.dev/docs/textinput

react native keep re-render the view every 10 ms when using AsyncStorage

I am newbie in ReactNative. ( I am very familiar with Raw Android)
Yesterday when I was using AsyncStorage ( incorrectly I think) , I met a problem that the View kept re-rendering every n millionseconds.
my code:
import React, { Component} from 'react';
import {Image, Platform, StyleSheet, Text, View, Button} from 'react-native'
import { AsyncStorage } from "react-native"
export default class StorageDemo extends Component{
constructor(props){
super(props)
AsyncStorage.setItem("visitTimes", 100)
this.state = {
isLoaded: false,
visitTimes: 0
}
}
readData = async () => {
try{
const result = await AsyncStorage.getItem("visitTimes")
this.setState(
{
visitTimes: result,
isLoaded: true
}
)
console.info("== loaded, this.state: ")
}catch(error){
console.error(error)
}
}
render() {
this.readData()
if(this.state.isLoaded){
return(
<View>
<Text>Loaded! </Text>
</View>
)
}else{
return(
<View>
<Text>Loading... </Text>
</View>
)
}
}
}
Also I opened a logcat window to check the log, I was shocked by the log: it kept re-rendering the View every 10 ms.
My environment:
Android SDK: 27
Windows
ReactNative 0.55
Device: VIVO Y67A ( Android 6.0 , 4G RAM)
code could be found here: https://github.com/sg552/react_native_lesson_demo/blob/master/screens/StorageDemo.js
I know my code is not correct (using async, await) , so my question is:
How to read from AsyncStorage and render it to page? How to correct my code?
thanks a lot!
Okay, so the problem is that you are calling your func this.readData() inside the render, and that function itself is calling setState which whenever is called, changes the state, which triggers a re-render on the component. So in this situation you have caused an infinite loop in the code, because setState calls render, which in turn calls setState again and you run out of memory.
To fix this quickly, you can remove the function call from your render, and add it to a button, so its only called when you want it to. Something like this:
import React, { Component} from 'react';
import {Image, Platform, StyleSheet, Text, View, Button} from 'react-native'
import { AsyncStorage } from "react-native"
export default class StorageDemo extends Component{
constructor(props){
super(props)
this.state = {
isLoaded: false,
visitTimes: 0
}
}
readData = async () => {
try{
const result = await AsyncStorage.getItem("visitTimes")
this.setState(
{
visitTimes: result,
isLoaded: true
}
)
console.info("== loaded, this.state: ")
}catch(error){
console.error(error)
}
}
render() {
if(this.state.isLoaded){
return(
<View>
<Text>Loaded! {this.state.visitTimes} </Text>
<Button
onPress={() => {
AsyncStorage.setItem("visitTimes", "100")
this.setState({isLoaded: false})
}}
title="Set Storage Item"
/>
</View>
)
}else{
return(
<View>
<Button
onPress={this.readData}
title="Load from async storage"></Button>
</View>
)
}
}
}
Try this and this should give you the value from localStorage!

React Native `new Function()` does not support ES6 syntax

CMD:
react-native init Test && react-native run-android
App.js:
export default class App extends Component {
render() {
new Function("person", "const { firstname } = person; alert(firstname);")({ firstname: "Test" });
}
}
Whenever the new function gets constructed and invoked, the app crashes stating: "SyntaxError: Unexpected token '{'. Expected an identifier name in const declaration" Only happens on Android.
Any help would be appreciated. Thanks!
React Native: v0.55.7
The react native documentation indicates that JavaScriptCore is generally used at runtime (V8 during debugging), but it's light on specifics as to how it is configured. One thing it does mention is that the native JavaScriptCore is used on iOS, while a different version is bundled with the app for user on Android.
Because Babel is used at compile time with react native to support ES5/ES6 features, it may be that the runtime is configured at a lower level of support. So when attempting to create code from a string at runtime, you may actually be running with a JavaScript interpreter that doesn't understand e.g., destructuring syntax.
You could try using Babel's transform at runtime to transpile your code:
import {transform} from 'babel-core';
export default class App extends Component {
render() {
const f = 'const { firstname } = person; alert(firstname);';
const result = transform(f, {
presets: ['es2015']
});
new Function("person", result.code)({ firstname: "Test" });
}
}
Can you create a const with a dynamic name? If it's possible, sorry about my lack of knowledge about that subject.
The error message said that a name to variable const is expected.
I hope it has been useful.
Best regards.
Try to change the style you create that function. In React Native is common to see arrow functions, that must be created outside your render method.
Note that your render method will be trigger every single time that your state changes. and it would be a waste of memory resources and unnecessary computing time
import React, {
Component
} from 'react';
import {
Text,
View,
StyleSheet
} from 'react-native';
export default class App extends Component {
//your custom function
myFunc = (param) => {
console.log(param)
return param
}
//your render method
render() {
const param = "Im a text"
//you could do this... i would never do that..
const myFuncInRender = () => { console.log('Im a stupid func')}
const myStupidFunc2 = new Function("person", "const { firstname } = person; alert(firstname);")({ firstname: "Test" });
return (
<View style={styles.container}>
<Text style={styles.paragraph}>
{this.myFunc(param)/* HERE is where you call the func*/}
</Text>
</View>
);
}
} // end from Class
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
backgroundColor: '#ecf0f1',
padding: 8,
alignItems:'center',
},
paragraph: {
margin: 24,
fontSize: 18,
fontWeight: 'bold',
textAlign: 'center',
},
});

Categories

Resources