Print value from a function. React-native - javascript

I have a problem about how to print a value,in a function, in react-native.
Basically I have a function that research in the DB some values, and I should print this values.
findUtente(cf) {
let params = {};
console.log(cf)
params = {
"Person.FiscalCode": cf
};
global.utente.db.localdb().find({
selector: params
})
.then(response => {
let utente = response.docs[0];
console.log ("utente: " + utente)
utente.Person.FirstName;
console.log ("utente.Person.FirstName: " + utente.Person.FirstName)
})
//.... catch...}); }
render() {
{this.findUtente(this.props.cf)}
return (
<View style={style.container}>
<View style={style.page}>
<KeyboardAwareScrollView>
<Text style={visualProfilo.text}>Name:</Text>
<Text style={visualProfilo.text1}>{Stamp Here the FirstName}</Text>
The value in the console log is print in the right way.
How can I print that value?
Thank you

You can use componentDidMount to call the method then you can set the value to state and then update value using setState then render state value
example:
state = {
FirstName: ''
}
componentDidMount(){
this.findUtente(this.props.cf)
}
findUtente(cf) {
let params = {};
console.log(cf)
params = {
"Person.FiscalCode": cf
};
global.utente.db.localdb().find({
selector: params
})
.then(response => {
let utente = response.docs[0];
this.setState({FirstName: utente.Person.FirstName})
})
//.... catch...}); }
render() {
return (
//everything remains same
<Text style={visualProfilo.text1}>{this.state.FirstName}</Text>
)
}

Related

How to check value is empty, or null in JavaScript?

I have a problem when I wanna get data from state, in console.log appears 2 values. I want remove the empty value, but I've run out of ways. How to remove an empty value?
class DetailOrderTracking extends Component {
constructor(props) {
super(props)
this.state = {
data: []
}
}
componentDidMount = async () => {
const { query } = this.props.router;
var getOrderTrackings = await OrderTrackingRepository.getOrderTracking(query.numberbill, query.courier);
if (getOrderTrackings.ordertracking.status.code == 200) {
var getManifest = getOrderTrackings.ordertracking.result.manifest;
this.setState({ data: getManifest });
}
}
render() {
const { data } = this.state;
console.log(data) // will print 2 values, first condition is empty value, and second condition has values (an example is in the image above)
return (
<div/>
)
}
}
This should do it:
render() {
const { data } = this.state;
if (data.length > 0){
console.log(data)
}
return (
<div/>
)
}

How to use filter function in multiple states at one time in react native

I want to filter the data from my multiple states at one time. But I am getting the data of only second state.
I have two states and both states are getting seprate data from seprate apis. Now I want to filter the data from it. thank youI don't know what i m doing wrong so pls help me and look at my code.
searchFeatured = value => {
const filterFeatured = (
this.state.latestuploads || this.state.featuredspeakers
).filter(item => {
let featureLowercase = (item.name + " " + item.title).toLowerCase();
let searchTermLowercase = value.toLowerCase();
return featureLowercase.indexOf(searchTermLowercase) > -1;
});
this.setState({
featuredspeakers: filterFeatured,
latestuploads: filterFeatured
});
};
class SearchPage extends Component {
constructor(props) {
super(props);
this.state = {
loading: false,
featuredspeakers: [],
latestuploads: [],
};
}
componentDidMount() {
axios
.all([
axios.get(
'https://staging.islamicmedia.com.au/wp-json/islamic-media/v1/featured/speakers',
),
axios.get(
'https://staging.islamicmedia.com.au/wp-json/islamic-media/v1/featured/latest-uploads',
),
])
.then(responseArr => {
//this will be executed only when all requests are complete
this.setState({
featuredspeakers: responseArr[0].data,
latestuploads: responseArr[1].data,
loading: !this.state.loading,
});
});
}
Using the || (OR) statement will take the first value if not null/false or the second. What you should do is combine the arrays
You should try something like
[...this.state.latestuploads, ... this.state.featuredspeakers].filter(item=>{});
Ahmed, I couldn't get your code to work at all - searchFeatured is not called anywhere. But I have some thoughts, which I hope will help.
I see that you're setting featuredspeakers and latestuploads in componentDidMount. Those are large arrays with lots of data.
But then, in searchFeatured, you are completely overwriting the data that you downloaded and replacing it with search/filter results. Do you really intend to do that?
Also, as other people mentioned, your use of the || operator is just returning the first array, this.state.latestuploads, so only that array is filtered.
One suggestion that might help is to set up a very simple demo class which only does the filtering that you want. Don't use axios at all. Instead, set up the initial state with some mocked data - an array of just a few elements. Use that to fix the filter and search functionality the way that you want. Here's some demo code:
import React from 'react';
import { Button, View, Text } from 'react-native';
class App extends React.Component {
constructor(props) {
super(props);
this.searchFeatured = this.searchFeatured.bind(this);
this.customSearch = this.customSearch.bind(this);
this.state = {
loading: false,
featuredspeakers: [],
latestuploads: [],
};
}
searchFeatured = value => {
// overwrite featuredspeakers and latestuploads! Downloaded data is lost
this.setState({
featuredspeakers: this.customSearch(this.state.featuredspeakers, value),
latestuploads: this.customSearch(this.state.latestuploads, value),
});
};
customSearch = (items, value) => {
let searchTermLowercase = value.toLowerCase();
let result = items.filter(item => {
let featureLowercase = (item.name + " " + item.title).toLowerCase();
return featureLowercase.indexOf(searchTermLowercase) > -1;
});
return result;
}
handlePress(obj) {
let name = obj.name;
this.searchFeatured(name);
}
handleReset() {
this.setState({
featuredspeakers: [{ name: 'Buffy', title: 'Slayer' }, { name: 'Spike', title: 'Vampire' }, { name: 'Angel', title: 'Vampire' }],
latestuploads: [{ name: 'Sarah Michelle Gellar', 'title': 'Actress' }, { name: 'David Boreanaz', title: 'Actor' }],
loading: !this.state.loading,
});
}
componentDidMount() {
this.handleReset();
}
getList(arr) {
let output = [];
if (arr) {
arr.forEach((el, i) => {
output.push(<Text>{el.name}</Text>);
});
}
return output;
}
render() {
let slayerList = this.getList(this.state.featuredspeakers);
let actorList = this.getList(this.state.latestuploads);
return (
<View>
<Button title="Search results for Slayer"
onPress={this.handlePress.bind(this, {name: 'Slayer'})}></Button>
<Button title="Search results for Actor"
onPress={this.handlePress.bind(this, {name: 'Actor'})}></Button>
<Button title="Reset"
onPress={this.handleReset.bind(this)}></Button>
<Text>Found Slayers?</Text>
{slayerList}
<Text>Found Actors?</Text>
{actorList}
</View>
);
}
};
export default App;
You should apply your filter on the lists separately then. Sample code below =>
const searchFeatured = value => {
this.setState({
featuredspeakers: customSearch(this.state.featuredspeakers, value),
latestuploads: customSearch(this.state.latestuploads, value)
});
};
const customSearch = (items, value) => {
return items.filter(item => {
let featureLowercase = (item.name + " " + item.title).toLowerCase();
let searchTermLowercase = value.toLowerCase();
return featureLowercase.indexOf(searchTermLowercase) > -1;
});
}

React Native - Unable to pass CheckBox value to another screen

I'm here to ask what's your idea to properly pass a CheckBox value to other screen?
Example, if a user checks a CheckBox then proceed to the Next Screen the value of the CheckBox should be displayed in that screen.
But in my code, my console.log gives an output of false(I don't understand why) and once I get to the next screen the state doesn't really pass because it's display is blank.
Here's my code
export default class tables extends Component {
constructor(props){
super(props)
this.state = {
...
check: {},
tbl_Merge: []
}
}
proceed_TO_Category = () => {
this.props.navigation.navigate('Category', {
userName : this.state.userName,
DineIn : this.state.DineIn,
tbl : this.state.tbl,
tbl_2nd : this.state.tbl_2nd,
tbl_Merge : this.state.tbl_Merge
});
console.log("CHECK ======> "+ this.state.tbl_Merge);
}
checkBox_Test = (table_NO) => {
const tbl_Merge = this.state.tbl_Merge;
const checkCopy = {...this.state.check}
if (checkCopy[table_NO]) {
checkCopy[table_NO] = false;
} else {
checkCopy[table_NO] = true;
}
this.setState({ check: checkCopy });
this.setState({ tbl_Merge: table_NO == this.state.tbl_Merge });
}
render() {
return(
<View>
....
<Flatlist
....
<CheckBox
value = { this.state.check[item.tbl_id] }
onChange = {() => this.checkBox_Test(item.tbl_id) }
/>
....
/>
....
<View>
<TouchableOpacity
onPress = {() => this.proceed_TO_Category()}>
<Text>Categories</Text>
</TouchableOpacity>
</View>
<View/>
)
}
}
Screen shot of Console.log in my proceed_TO_Category.
checkBox_Test = (table_NO) => {
const tbl_Merge = this.state.tbl_Merge;
const checkCopy = {...this.state.check}
if (checkCopy[table_NO]) {
checkCopy[table_NO] = false;
} else {
checkCopy[table_NO] = true;
}
this.setState({ check: checkCopy, tbl_Merge: table_NO == this.state.tbl_Merge }); // 1. Edit
}
Edit: We should not use setState consecutively. Because setState is async func. If you want to call a function after setState process with the help of callback function,setState(update, callback);
you defined tbl_Merge as an array, but while you set it to state, you set it as a boolean.

Delete Item by Key, Firebase React Native

I have a simple Notes React Native app and I am able to add and get data to it, but I am not sure how to remove/update data. The main problem is in getting the part where I tell firebase which data to remove. How can I pass a firebase key to a 'delete' function that takes the key as parameter and remove it from firebase.
I'm an absolute beginner at React Native, my code is the following:
export default class App extends React.Component {
constructor(props) {
super(props);
this.state = {
all_notitas: [],
notita_text: ''
};
};
componentWillMount() {
const notitasRef = firebase.database().ref('notitas');
this.listenForNotitas(notitasRef);
};
listenForNotitas = (notitasRef) => {
notitasRef.on('value', (dataSnapshot) => {
var aux = [];
dataSnapshot.forEach((child) => {
aux.push({
date: child.val().date,
notita: child.val().notita
});
});
this.setState({all_notitas: aux});
});
}; // listenForNotitas
render() {
let show_notitas = this.state.all_notitas.map((val, key) => {
return (
<Notita
key={key}
keyval={key}
val={val}
eventDeleteNotita={()=>this.deleteNotita(key)}> // I THINK THIS IS THE PROBLEM
</Notita>
);
});
return (
<View style={styles.container}>
<View style={styles.header}>
<Text style={styles.headerText}>NOTITAS</Text>
</View>
<ScrollView style={styles.scrollContainer}>
{show_notitas}
</ScrollView>
<View style={styles.footer}>
<TouchableOpacity
style={styles.addButton}
onPress={this.addNotita.bind(this)}>
<Text style={styles.addButtonText}>+</Text>
</TouchableOpacity>
<TextInput
style={styles.textInput}
placeholder='>>> Escribir notita'
placeholderTextColor='white'
underlineColorAndroid='transparent'
onChangeText={(notita_text) => (this.setState({notita_text}))}
value={this.state.notita_text}>
</TextInput>
</View>
</View>
);
}
addNotita() {
if (this.state.notita_text) {
var d = new Date();
dataForPush = {
'date': d.getDate() + '-' + d.getMonth() + '-' + d.getFullYear(),
'notita': this.state.notita_text
};
firebase.database().ref('notitas').push(dataForPush);
this.state.all_notitas.push(dataForPush);
this.setState(
{
all_notitas: this.state.all_notitas,
notita_text: '', // Limpiar input
}
)
} // end if
} // addNotita
When I do 'console.log(key)', it returns an int like 0, 1, 2, etc. It should return a firebase key like '-LRtghw8CjMsftSAXMUg' for example. I don't know what I am doing wrong and how to fix it.
deleteNotita(key) {
firebase.database().ref('notitas').child('' + key).remove()
/*
let updates = {};
console.log(key);
console.log(updates['/notitas/' + key]);
updates['/notitas/' + key] = null;
firebase.database().ref().update(updates); */
this.state.all_notitas.splice(key, 1);
this.setState({all_notitas: this.state.all_notitas});
} // deleteNotita
}
You're dropping the key from Firebase when you're adding the notes to aux. The solution is to also keep the key from Firebase in there:
notitasRef.on('value', (dataSnapshot) => {
var aux = [];
dataSnapshot.forEach((child) => {
aux.push({
date: child.val().date,
notita: child.val().notita,
id: child.key
});
});
this.setState({all_notitas: aux});
}
And then pass that value to deleteNotita with:
this.deleteNotita(val.id)

How to search data efficiently with React Native ListView

I am trying to implement a filter and search function that would allow user to type in keyword and return result(array) and re-render the row
This is the event arrays that being passed in into the createDataSource function
The problem I am having now is my search function can't perform filter and will return the entire parent object although I specifically return the indexed object.
Here's what I got so far
class Search extends Component {
state = { isRefreshing: false, searchText: '' }
componentWillMount() {
this.createDataSource(this.props);
}
componentWillReceiveProps(nextProps) {
this.createDataSource(nextProps);
if (nextProps) {
this.setState({ isRefreshing: false })
}
}
createDataSource({ events }) {
const ds = new ListView.DataSource({
rowHasChanged: (r1, r2) => r1 !== r2
});
this.dataSource = ds.cloneWithRows(events);
}
//return arrays of event from events
renderRow(event) {
return <EventItem event={event} />;
}
onRefresh = () => {
this.setState({ isRefreshing: true });
this.props.pullEventData()
}
setSearchText(event) {
let searchText = event.nativeEvent.text;
this.setState({ searchText })
var eventLength = this.props.events.length
var events = this.props.events
const filteredEvents = this.props.events.filter(search)
console.log(filteredEvents);
function search() {
for (var i = 0; i < eventLength; i++) {
if (events[i].title === searchText) {
console.log(events[i].title)
return events[i];
}
}
}
}
render() {
const { skeleton, centerEverything, container, listViewContainer, makeItTop,
textContainer, titleContainer, descContainer, title, desc, listContainer } = styles;
return(
<View style={[container, centerEverything]}>
<TextInput
style={styles.searchBar}
value={this.state.searchText}
onChange={this.setSearchText.bind(this)}
placeholder="Search" />
<ListView
contentContainerStyle={styles.listViewContainer}
enableEmptySections
dataSource={this.dataSource}
renderRow={this.renderRow}
refreshControl={
<RefreshControl
refreshing={this.state.isRefreshing}
onRefresh={this.onRefresh}
title="Loading data..."
progressBackgroundColor="#ffff00"
/>
}
/>
</View>
)
}
}
As you can see from the image above, my code requires me to type in the full query text to display the result. And it displays all the seven array objects? why's that?
The syntax of Array.prototype.filter is wrong... it should take a callback that will be the item being evaluated for filtering.. if you return true it will keep it.
function search(event) {
return ~event.title.indexOf(searchText)
}
You could even make the inline like..
const filteredEvents = this.props.events.filter(event => ~event.title.indexOf(searchText))
For understanding my use of ~, read The Great Mystery of the Tilde.
Since filter returns a new array, you should be able to clone your dataSource with it. If you didn't use filter, you would have to call events.slice() to return a new array. Otherwise, the ListView doesn't pickup the changes.

Categories

Resources