React Native states not updating value after changing value - ios

I am new to React-Native and its states, here I am stuck with a problem (using dummy data but my problem is same) all I want to achieve is get the latest JSONARRAY fetched from the state, based on button clicks when I click on button one it should only return [{"one":"oneKey"},{"key":"mutatedFruit"}] and similar approach for other buttons as well any help is appreciated
I have attached my
expo snack code here

hope the below code helps ,
import * as React from 'react';
import { Text, View,Button, StyleSheet } from 'react-native';
import Constants from 'expo-constants';
// You can import from local files
import AssetExample from './components/AssetExample';
const data = [
{"joinedUsers":[{"one":"oneKey"}],"key":"mango"}
,{"joinedUsers":[{"two":"twoKey"}],"key":"apple"}
,{"joinedUsers":[{"three":"threeKey"}],"key":"banana"}
,{"joinedUsers":[{"four":"fourKey"}],"key":"kiwi"}];
// or any pure javascript modules available in npm
import { Card } from 'react-native-paper';
export default class App extends React.Component {
constructor(props){
super(props);
this.state={
selectedPosition:0,
valueArr : []
}
}
componentDidMount(){
let newVal = [];
newVal.push(data[0].joinedUsers[0])
newVal.push({"key":"mutatedFruit"})
this.setState({valueArr:newVal})
}
setValues = (position) => {
let newVal = [];
newVal.push(data[position].joinedUsers[0])
newVal.push({"key":"mutatedFruit"})
this.setState({valueArr:newVal})
}
render() {
const value = data[this.state.selectedPosition].joinedUsers
value.push({"key":"mutatedFruit"})
return (
<View style={styles.container}>
<Button title='ONE'
onPress={()=>this.setValues(0)}></Button>
<Button title='TWO'
onPress={()=>this.setValues(1)}></Button>
<Button title='THREE'
onPress={()=>this.setValues(2)}></Button>
<Button title='FOUR'
onPress={()=>this.setValues(3)}></Button>
<Text>{JSON.stringify(this.state.valueArr)}</Text>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
paddingTop: Constants.statusBarHeight,
backgroundColor: '#ecf0f1',
padding: 8,
flexDirection:'column'
},
paragraph: {
margin: 24,
fontSize: 18,
fontWeight: 'bold',
textAlign: 'center',
},
});

EDIT: Based on your comment, it sounds like your issue is you don't want the same value added multiple times. In that case, this should fix it:
export default class App extends React.Component {
state= {
selectedPosition:0,
}
render() {
const value = data[this.state.selectedPosition].joinedUsers
value[0]["key"] = "mutatedFruit"
return (
<View style={styles.container}>
<Button title='ONE'
onPress={()=>this.setState({selectedPosition:0})}></Button>
<Button title='TWO'
onPress={()=>this.setState({selectedPosition:1})}></Button>
<Button title='THREE'
onPress={()=>this.setState({selectedPosition:2})}></Button>
<Button title='FOUR'
onPress={()=>this.setState({selectedPosition:3})}></Button>
<Text>{JSON.stringify(value)}</Text>
</View>
);
}
}

Related

React Native NOT rendering data from database on IOS

I have problem with render data on IOS Simulator. Render is work properly on website, but on IOS I still got stuck on "Loading.." text.
Here is my code:
import React from 'react'
import { useState } from 'react';
import { useEffect } from 'react';
import { SafeAreaView, Text, View, StyleSheet, Image, Alert } from 'react-native';
import { Card } from 'react-native-paper'
import firebase from 'firebase'
import Button from '../components/Button'
import Background from '../components/Background'
import TopBar from '../components/TopBar'
export default function HomeScreen({ navigation }) {
const [data, setData] = useState([])
const sampleData = [{id:0, title:"One"}, {id:1, title: "Two"}]
useEffect(() =>
{
const donorsData = [];
firebase.database()
.ref("testdb")
.orderByChild("isDonor")
.equalTo(true)
.once("value")
.then((results) => {
results.forEach((snapshot) => {
donorsData.push(snapshot.val());
});
setData(donorsData);
});
}, [])
const card = data.length > 0
? data.map(item =>
{
return <Card key={item.uid} style={{ marginBottom: 20, borderRadius: 10, }}>
<Text>{item.name}</Text>
<Text>{item.description}</Text>
<Image src={item.photo}></Image>
</Card>
})
: <Text>Loading...</Text>
return (
<View style={styles.container}>
{card}
</View>
);
}
On website is everything ok Website Screen
But on IOS Simulator I got only Loading
IOS Screen
I tried a lot of solutions found here, but no one works with this case. I think is probably because iOS doesn't have data? When I put console log at to top of return, I got nothing.
This might be a race condition error. You shouldn't rely on the data being fetched within 1500ms.
If that doesn't work. Make sure your result from firebase is correct.
Maybe something like this?
const [data, setData] = useState([])
const fetchDonorData = () => {
firebase.database()
.ref("testdb")
.orderByChild("isDonor")
.equalTo(true)
.once("value")
.then((results) => {
console.log({result}) //Make sure the data looks the way you want it
const mappedResult = results?.map(snapshot => snapshot.val())
setData(mappedResult)
})
}
useEffect(() => {
fetchDonorData()
}, [])
const renderItem = ({item}) =>
<Card style={{ marginBottom: 20, borderRadius: 10, }}>
<Text>{item.name}</Text>
<Text>{item.description}</Text>
<Image src={item.photo}></Image>
</Card>
return (
<View style={styles.container}>
<FlatList
data={data}
renderItem={renderItem}
keyExtractor={({item}) => item.uid}
ListEmptyComponent={<Text>Loading...</Text>}
/>
</View>
)

text string must be rendered with <text> component error only on ios

I'm getting this weird error when I'm running my code on Expo Go on IOS
I'm new to react native and I don't know what to do
This is my code:
import React, { Component } from 'react';
import { Button, StyleSheet, Text, TextInput, View } from 'react-native';
export default class ButtonBasics extends Component {
_onPressButton() {
alert("Don't touch that button!")
}
render() {
return (
<View style={styles.container}>
<View style={styles.buttonContainer}>
<text>Press the button</text>
<Button title="Press" onPress={this._onPressButton} color="#57a9af" />
<View/>
</View>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#d6f0f2',
alignItems: 'center',
justifyContent: 'center',
},
});
Well There are multiple problems with your Code,
<text> is not a valid component. It is <Text> with Capital T. You have imported the right Component but using the wrong Tag.
You have three end tags. While you have only two start tags.
So your code should be
import React, { Component } from 'react';
import { Button, StyleSheet, Text, TextInput, View } from 'react-native';
export default class ButtonBasics extends Component {
_onPressButton() {
alert("Don't touch that button!")
}
render() {
return (
<View style={styles.container}>
<View style={styles.buttonContainer}>
<Text>Press the button</Text>
<Button title="Press" onPress={this._onPressButton} color="#57a9af" />
<View/>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#d6f0f2',
alignItems: 'center',
justifyContent: 'center',
},
});

react-native - this.porps.inGrid is not a function

I'm trying to display a nested array containing numbers. The array has 6 elements (arrays). Each nested array contains 6 further elements/numbers. I'm trying to display each number in a Square component. I've got an error: this.props.inGrid.foreach is not a function.
import React, { Component, PropTypes } from 'react';
import { View, StyleSheet } from 'react-native';
import Square from './Square';
import * as globalStyles from '../styles/global';
export default class Grid extends Component {
render() {
const row = [];
this.props.inGrid.foreach((r, i) => {
row.push(
<Square key={i} sqValue={r[i]} />
);
});
return (
<View style={styles.grid}>
{row}
</View>
);
}
}
Grid.propTypes = {
numbers: PropTypes.object
};
const styles = StyleSheet.create({
grid: {
backgroundColor: globalStyles.BG_COLOR,
flexDirection: 'row',
padding: 20,
justifyContent: 'center'
}
});
Below is the Square component:
import React, { PropTypes } from 'react';
import { View, Text, StyleSheet } from 'react-native';
import * as globalStyles from '../styles/global';
const Square = ({ sqValue }) => {
return (
<View style={styles.square}>
<Text>{sqValue}</Text>
</View>
);
};
Square.propTypes = {
sqValue: PropTypes.number
};
const styles = StyleSheet.create({
square: {
backgroundColor: globalStyles.BAR_COLOR,
width: 50,
height: 50,
borderWidth: 1,
borderStyle: 'solid',
borderColor: 'red'
}
});
export default Square;
What am I doing wrong?
It appears that you're calling:
this.props.inGrid.foreach
but the function is actually called forEach

App navigation in React Native : maximum call stack size exceeded

I'm using ReactNative to create an iOS app. But I encountered an error I don't know how to fix.
I wanted to create a button for navigating to another scene. I followed Dark Army's tutorial on RN navigation and used the source code provided. I double checked everything and all seemed fine. But the error I mentioned pops up.
Here's the code I have done so far:
Index.ios.js:
import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
} from 'react-native';
var Navigation = require('./DARNNavigator');
class QayProject extends Component {
render() {
return (
<Navigation></Navigation>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#FFF5E7',
},
welcome: {
fontSize: 20,
textAlign: 'center',
margin: 10,
},
instructions: {
textAlign: 'center',
color: '#333333',
marginBottom: 5,
},
});
AppRegistry.registerComponent('QayProject', () => QayProject);
DARNNavigator:
'use strict';
import React , {Component} from 'react';
import{
View,
Navigator
} from 'react-native';
const FirstPage = require('./FirstPage');
const SecondPage = require('./SecondPage');
class DARNNavigator extends React.Component{
constructor(props) {
super(props);
}
render() {
var initialRouteID = 'first';
return (
<Navigator
style={{flex:1}}
initialRoute={{id: initialRouteID}}
renderScene={this.navigatorRenderScene}/>
);
}
navigatorRenderScene(route, navigator) {
switch (route.id) {
case 'first':
return (<FirstPage navigator={navigator} route={route} title="FirstPage"/>);
case 'second':
return (<SecondPage navigator={navigator} route={route} title="SecondPage"/>);
}
}
}
module.exports = DARNNavigator;
FirstPage:
import React, { Component } from 'react';
import{
View,
Navigator,
Button,
AppRegistry,
StyleSheet
} from 'react-native';
export default class FirstPage extends Component {
constructor(props) {
super(props);
this.state={ id:'first' }
}
render() {
return (
<View style={styles.container}>
<Button
onPress={this.props.navigator.push({ id:'second' })}
title="Next"
color="#FFB200"
/>
</View>
)
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
},
welcome: {
fontSize: 20,
textAlign: 'center',
margin: 10,
},
instructions: {
textAlign: 'center',
color: '#333333',
marginBottom: 5,
},
});
module.exports = FirstPage;
SecondPage:
import React, { Component } from 'react';
import {
View,
Text,
Navigator,
StyleSheet
} from 'react-native';
export default class SecondPage extends Component {
constructor(props) {
super(props);
this.state={
id:'second'
}
}
render() {
return (
<View style={styles.container}>
<Text style={styles.title}>
Hello!
</Text>
</View>
)
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
},
welcome: {
fontSize: 20,
textAlign: 'center',
margin: 10,
},
instructions: {
textAlign: 'center',
color: '#333333',
marginBottom: 5,
},
});
module.exports = SecondPage;
Don't use that library. They don't even have ONE single star on Github (not that it's the measure of a library's worth, I'm just saying there are more proven libraries available). The best and most straightforward I've found so far is "react-native-navigation" (https://github.com/wix/react-native-navigation). A lot of people like "react-native-router-flux" as well but I personally don't.
Sorry, I don't have time to read the code right now, I may later. But my suggestion for now is to try out react-native-navigation. It's seriously amazing.
I suggest to follow the official guide of React Native and use the built-in Navigator component.
Using Navigators React Native
I never saw that error, but if it will come after a lot of navigation steps, you should take a look at the resetTo function. It will clear the navigation stack. This makes sense for example when you are navigating back to the home screen of your app.

Super expression must either be null or a function, react native 0.26.3

I am a newbie in react native.
I have one similar problem in different projects. When I try to compile my project, I see this problem. Why this error is appear?
P.S. I am learning react-native by tutorials like a appcoda.com
Picture of my error
Featured.js
'use strict';
var React = require('react-native');
var{
StyleSheet,
View,
Text,
Component
} = React;
var styles = StyleSheet.create({
description:{
fontSize: 20,
backgroundColor: 'white'
},
container:{
flex: 1,
justifyContent: 'center',
alignItems: 'center'
}
});
class Featured extends Component{
render() {
return(
<View style = {styles.container}>
<Text style = {styles.description}>
Featured tab
</Text>
</View>
);
}
}
module.exports = Featured;
Change your import statement as below
import React, { Component } from 'react';
import {
StyleSheet,
View,
Text,
} from 'react-native';

Resources