How to solve infinite loop in JSX? - javascript

Im trying to map my userForm state to render each by each , but the map function sometimes returns me as undefiend and sometimes as an react infinite loop and I'm not finding a way to solve it, somene could help me ?
my code:
const FormScreen = async({route}) => {
const [userForm, setuserForm] = useState([]);
if (userForm.length > 0) {
console.log(userForm,'campos:',userForm.fields);
return;
} else {
setuserForm(await JSON.parse(route.params.paramKey));
}
{...}
return (
<SafeAreaView style={{flex: 1}}>
<View style={styles.container}>
<Text style={styles.textStyle}>
COLLECTION :
</Text>
{userForm.map((item) => (
<Text keys={item.fields}>test</Text>
))}
</View>
</SafeAreaView>
);
};

Move setuserForm(await JSON.parse(route.params.paramKey)); into a useEffect hook.
https://reactjs.org/docs/hooks-effect.html

Related

RN - Map directly from state syntax

I'm trying to map an array from state - but confused re the correct syntax - can anyone please advise where i'm going wrong:
This is what I have at the mo:
newsStorys = () => {
return (
{this.state.newsFeed.map((a) => {
<View style={ModalStyles.newsArticle}>
<Text style={ModalStyles.newsDate}>{a.date}</Text>
<Text style={ModalStyles.newsTitle}>{a.title}</Text>
<Text style={ModalStyles.newsDesc}>
{a.story}
</Text>
</View>
}
}
);
};
I'm not sure if that is the whole code of your component, but I can see three things.
If newsFeed is not initialized when component first render (let's say it is undefined yet), then newsFeed.map()will throw an exception.
You are not returning anything from map call. you should write something like this:
newsStorys = () => {
if (!this.state.newsFeed) return null;
return this.state.newsFeed.map((a) => ({ // <--- note the parentheses here, you don't have it
<View style={ModalStyles.newsArticle}>
<Text style={ModalStyles.newsDate}>{a.date}</Text>
<Text style={ModalStyles.newsTitle}>{a.title}</Text>
<Text style={ModalStyles.newsDesc}>
{a.story}
</Text>
</View>
});
);
};
If you want to avoid the parentheses, then you need to explicitly return something, like this:
this.state.newsFeed.map((a) => {
return (
<View style={ModalStyles.newsArticle}>
<Text style={ModalStyles.newsDate}>{a.date}</Text>
<Text style={ModalStyles.newsTitle}>{a.title}</Text>
<Text style={ModalStyles.newsDesc}>
{a.story}
</Text>
</View>
);
});
It is possible that you need an extra view to wrap the list of views returned by map.
Also you need to provide a unique key to each view, so React can keep track on them.
<View style={ModalStyles.newsArticle} key={'nome unique value'}>
...
</View>
Finally I think it would be better using a FlatList instead of map.
Cheers!
Had a play and a good dig around the web and found the syntax answer: (Thanks to Bruno for the Key and pointers).
newsStorys = () => {
return this.state.newsFeed.map((value, index) => {
return (
<View style={ModalStyles.newsArticle} key={index}>
<Text style={ModalStyles.newsDate}>{value.date}</Text>
<Text style={ModalStyles.newsTitle}>{value.title}</Text>
<Text style={ModalStyles.newsDesc}>{value.story}</Text>
</View>
);
});
};
Try this
newsStorys = () => (
this.state.newsFeed.map(({ date, story, title }, index) =>
<View key={`news-${index}`} style={ModalStyles.newsArticle}>
<Text style={ModalStyles.newsDate}>{date}</Text>
<Text style={ModalStyles.newsTitle}>{title}</Text>
<Text style={ModalStyles.newsDesc}>{story}</Text>
</View>
));

Unable to loop and render FlatList inside .map function react-native

I am trying to render a FlatList inside a component. The Component itself is inside a ScrollView.
I am using map function to loop through the data to pass into the component.
Earlier I was using ScrollView instead of FlatList. It was working fine, but was rendering slow. So I decided to use FlatList.
Here's my code:
renderComp(){
const { filtersView,cats,cats_title, clearStyle} = styles;
const data = this.props.ingreds;
const arr = Object.entries(data);
return arr.map(i=> {
const name= i[0];
const items_obj = i[1];
const items = Object.values(items_obj);
return(
<View key={name} style= {filtersView}>
<View style={cats}>
<Text style ={cats_title}>{name}</Text>
<Text style={clearStyle}>Clear All</Text>
</View>
<View style={{justifyContent:'flex-start', alignItems:'flex-start'}}>
<FlatList
style={{ marginRight:6}}
data={items}
keyExtractor={(x,i)=> i.toString()}
renderItem={({item}) =>{
this.renderItems(item)
}}
/>
</View>
</View>
)
})
}
And here's the ScrollView Component:
<ScrollView contentContainerStyle={{alignItems:'flex-start',
justifyContent:'flex-start',flex:1, height:72}} >
{this.renderComp()}
</ScrollView>
And The loop stops after one iteration.
Here's the output: https://i.stack.imgur.com/yM151.png
Any suggestions?
ReactNative FlatList renderItem method should return a ?React.Element component. In your case either use return this.renderItems or skip the inner brackets.
https://facebook.github.io/react-native/docs/flatlist#renderitem
({item}) => this.renderItems(item)}

Undefined is not an object evaluating this.state/this.props

How do I bind a function outside of scope in React Native? I'm getting the errors:
undefined is not an object evaluating this.state
&
undefined is not an object evaluating this.props
I'm using the render method to evoke renderGPSDataFromServer() when the data has been loaded. The problem is, I'm trying to use _buttonPress() and calcRow() inside of renderGPSDataFromServer(), but I'm getting those errors.
I've added
constructor(props) {
super(props);
this._buttonPress = this._buttonPress.bind(this);
this.calcRow = this.calcRow.bind(this);
to my constructor and I've changed _buttonPress() { to _buttonPress = () => { and still nothing.
I think I understand the problem but I don't know how to fix it:
renderLoadingView() {
return (
<View style={[styles.cardContainer, styles.loading]}>
<Text style={styles.restData}>
Loading ...
</Text>
</View>
)
}
_buttonPress = () => {
this.props.navigator.push({
id: 'Main'
})
}
renderGPSDataFromServer =() => {
const {loaded} = this.state;
const {state} = this.state;
return this.state.dataArr.map(function(data, i){
return(
<View style={[styles.cardContainer, styles.modularBorder, styles.basePadding]} key={i}>
<View style={styles.cardContentLeft}>
<TouchableHighlight style={styles.button}
onPress={this._buttonPress().bind(this)}>
<Text style={styles.restData}>View Video</Text>
</TouchableHighlight>
</View>
<View style={styles.cardContentRight}>
<Text style={styles.restData}>{i}</Text>
<View style={styles.gpsDataContainer}>
<Text style={styles.gpsData}>
{Number(data.lat).toFixed(2)}</Text>
<Text style={styles.gpsData}>{Number(data.long).toFixed(2)}</Text>
</View>
<Text style={styles.gpsData}>
{this.calcRow(55,55).bind(this)}
</Text>
</View>
</View>
);
});
}
render = ()=> {
if (!this.state.loaded) {
return this.renderLoadingView();
}
return(
<View>
{this.renderGPSDataFromServer()}
</View>
)
}};
How do I go about fixing this and in this case what is the problem?
this.props are read-only
React docs - component and props
And therefore a component shouldn't try a to modify them let alone mutate them as you are doing here:
_buttonPress = () => {
this.props.navigator.push({
id: 'Main'
})
}
I'd suggest using state instead:
_buttonPress = () => {
this.setState = {
...this.state,
navigator: {
...this.state.navigator,
id: 'Main'
}
}
}
Regarding your binding issue:
the .map method takes a 2nd argument that is used to set the value of this when the callback is invoked.
In the context of your question, you just need to pass thisas the 2nd argument to you .map method to bind the components scope's this to it.
This is happening because, the function inside the map method creates a different context. You can use arrow functions as the callback in the map method for lexical binding. That should solve the issue you are having.
renderGPSDataFromServer =() => {
const {loaded} = this.state;
const {state} = this.state;
return this.state.dataArr.map((data, i) => {
return(
<View style={[styles.cardContainer, styles.modularBorder, styles.basePadding]} key={i}>
<View style={styles.cardContentLeft}>
<TouchableHighlight style={styles.button}
onPress={this._buttonPress().bind(this)}>
<Text style={styles.restData}>View Video</Text>
</TouchableHighlight>
</View>
<View style={styles.cardContentRight}>
<Text style={styles.restData}>{i}</Text>
<View style={styles.gpsDataContainer}>
<Text style={styles.gpsData}>
{Number(data.lat).toFixed(2)}</Text>
<Text style={styles.gpsData}>{Number(data.long).toFixed(2)}</Text>
</View>
<Text style={styles.gpsData}>
{this.calcRow(55,55).bind(this)}
</Text>
</View>
</View>
);
});
}
Also, once you've used arrow functions in the class function definition you
don't need to bind them in constructor like:
constructor(props) {
super(props);
this._customMethodDefinedUsingFatArrow = this._customMethodDefinedUsingFatArrow.bind(this)
}
Also, once you have defined class functions as arrow functions, you
don't need to use the arrow functions while calling them either:
class Example extends React.Component {
myfunc = () => {
this.nextFunc()
}
nextFunc = () => {
console.log('hello hello')
}
render() {
// this will give you the desired result
return (
<TouchableOpacity onPress={this.myFunc} />
)
// you don't need to do this
return (
<TouchableOpacity onPress={() => this.myFunc()} />
)
}
}
not sure if this is the problem, but I think is code is wrong, and may be potentially causing your issue.
<View style={styles.cardContentLeft}>
<TouchableHighlight style={styles.button}
onPress={this._buttonPress().bind(this)}>
<Text style={styles.restData}>View Video</Text>
</TouchableHighlight>
</View>
specifically this line onPress={this._buttonPress().bind(this)}>
you are invoking the function and binding it at the same time.
The correct way to do this would be so
onPress={this._buttonPress.bind(this)}>
this way the function will be called only onPress.
You are going in the right direction, but there is still a minor issue. You are passing a function to your map callback that has a different scope (this) than your component (because it is not an arrow function), so when you do bind(this), you are rebinding your callback to use the scope from map. I think this should work, it basically turns the callback that you pass to map into an arrow function. Also, since you bind your function in the constructor, you do not need to do it again:
// The constructor logic remains the same
// ....
renderLoadingView() {
return (
<View style={[styles.cardContainer, styles.loading]}>
<Text style={styles.restData}>
Loading ...
</Text>
</View>
)
}
_buttonPress = () => {
this.props.navigator.push({
id: 'Main'
})
}
renderGPSDataFromServer =() => {
const {loaded} = this.state;
const {state} = this.state;
return this.state.dataArr.map((data, i) => {
return(
<View style={[styles.cardContainer, styles.modularBorder, styles.basePadding]} key={i}>
<View style={styles.cardContentLeft}>
<TouchableHighlight style={styles.button}
onPress={this._buttonPress}>
<Text style={styles.restData}>View Video</Text>
</TouchableHighlight>
</View>
<View style={styles.cardContentRight}>
<Text style={styles.restData}>{i}</Text>
<View style={styles.gpsDataContainer}>
<Text style={styles.gpsData}>
{Number(data.lat).toFixed(2)}</Text>
<Text style={styles.gpsData}>{Number(data.long).toFixed(2)}</Text>
</View>
<Text style={styles.gpsData}>
{this.calcRow(55,55).bind(this)}
</Text>
</View>
</View>
);
});
}
render = ()=> {
if (!this.state.loaded) {
return this.renderLoadingView();
}
return(
<View>
{this.renderGPSDataFromServer()}
</View>
)
}};

React-Native: Cannot access state values or any methods declared from renderRow

I have a listview, whenever user clicks on an item, i want to do something with onPress (touchable highlight).
I tried defining function then calling them in onPress but they didnt work.
first i defined a function like this :
constructor(props) {
super(props);
this.state = {
dataSource: new ListView.DataSource({
rowHasChanged: (row1, row2) => row1 !== row2,
}),
loaded: false,
};
this._dosome = this._dosome.bind(this);
}
_dosome(dd){
console.log(dd);
}
Then :
render(){
if (!this.state.loaded) {
return this.renderLoadingView();
}
return (
<View style={{
flex: 1
}}>
<ListView
dataSource={this.state.dataSource}
renderRow={this.renderRow}
style={styles.listView}
/>
</View>
);
}
renderRow(data) {
var header = (
<View>
<View style={styles.rowContainer}>
<View style={styles.textContainer}>
<Text style={styles.title}>{data.nid}</Text>
<Text style={styles.description} numberOfLines={0}>{data.title}</Text>
</View>
</View>
<View style={styles.separator}></View>
</View>
);
///////////
var cid = [];
var content = [];
for(let x=0; x < Object.keys(data.course).length; x++){
cid[x] = data.course[x].course_id;
content.push(
<TouchableHighlight
underlayColor='#e3e0d7'
key={x}
onPress={ this._dosome } //// **** PROBLEM HERE ****
style={styles.child}
>
<Text style={styles.child}>
{data.course[x].title}
</Text>
</TouchableHighlight>
);
}
console.log(cid);
var clist = (
<View style={styles.rowContainer}>
{content}
</View>
);
////////////
return (
<Accordion
header={header}
content={clist}
easing="easeOutCubic"
/>
);
}
renderLoadingView() {
return (
<View style={styles.loading}>
<Text style={styles.loading}>
Loading Courses, please wait...
</Text>
</View>
);
}
}
But it didnt worked, error :
TypeError: Cannot read property '_dosome' of null(…)
I tried calling it onPress like this :
onPress={ this._dosome.bind(this) }
didn't help
onPress={ ()=> {this._dosome.bind(this)}}
didn't help
onPress={ console.log(this.state.loaded)}
even i cannot even access props defined in constructor. it don't know what is "this" !
I tried to define the function other way like this :
var _dosome = (dd) => {
console.log(dd);
};
I tried defining the _dosome before render, after render, inside render, inside renderRow, and after renderRow. all same results.
I did check lots of tutorials, lots of sample apps on rnplay, lots of threads in stackoverflow, lots of examples, but none of them worked for me.
any solutions/ideas?
Any help is highly appreciated. i'm struggling with this issue for 2 days now.
Thanks in Advance!
How to solve your problem
Change
<ListView
dataSource={this.state.dataSource}
renderRow={this.renderRow}
style={styles.listView}
/>
To
<ListView
dataSource={this.state.dataSource}
renderRow={data => this.renderRow(data)}
style={styles.listView}
/>
Or
<ListView
dataSource={this.state.dataSource}
renderRow={this.renderRow.bind(this)}
style={styles.listView}
/>
Why?
As you already know(since you are trying to solve the problem by using arrow function and bind), to call renderRow, the caller should be in the same context as the component itself.
But this connection is lost in renderRow={this.renderRow}, which created a new function(new context).

ComponentWillmount Fetch returning Null?

My app is always loading, When i drop a debugger around and add a watch onto variable list & res , i get not available.
I'm not exactly sure what's the problem or am i even debugging it correctly?
please advice. I'm trying to achieve Loaded by loading the json into the list.
Update:
I just did a console log and saw data
console.log(this.state.list);
var facemashTab = React.createClass({
getInitialState: function() {
return {
list: [],
currentIndex: 0
};
},
componentWillMount: function() {
fetch('https://randomuser.me/api/?results=5')
.then(res => res.json())
.then(res => this.setState({ list: res }));
},
render: function() {
var contents;
if (!this.state.list.length) {
contents = (
<View style={ styles.loading }>
<Text style={ styles.loadingText }>Loading</Text>
<ActivityIndicatorIOS />
</View>
)
} else {
contents = (
<View style={ styles.content }>
<Text>Loaded</Text>
</View>
)
}
return (
<View style={ styles.container }>
<View style={ styles.header }>
<Text style={ styles.headerText }>XXX</Text>
</View>
<View style={ styles.content }>
{ contents }
</View>
</View>
);
}
});
Not sure if this is the problem, but from my understanding setState inside componentWillMount will not trigger a render phase ? could you try componentDidMount

Categories