react native rendering data prematurely - javascript

We have a feature where users can discuss in 3 different topics. This topics are displayed with a flatlist:
<View style={{ position: 'absolute', left: 0, top: 0 }}>
<FlatList
horizontal
data={categories}
extraData={
selectedCategory // for single item
}
style={styles.flatList}
renderItem={({ item: rowData }) => (
<TouchableOpacity
onPress={() => setSelectedCategory(rowData)}
style={rowData === selectedCategory ? styles.selected : styles.unselected}
>
<Text style={{ fontWeight: 'bold', color: '#FFFFFF', padding: 6 }}>
{ rowData }
</Text>
</TouchableOpacity>
)}
keyExtractor={(item, index) => item.toString()}
/>
</View>
our issue is when we change topics, the data is rendering prematurely, thus rendering the wrong category data several times. a screen grab here can show you the issue better that I can explain it in words: https://imgur.com/a/koCa6Pr
Once it stops, it might settle and display the correct topic data, or it might show another topics data (such as moves when you are on memes).
Here is our code to display a topic's data:
useEffect(() => {
getCollection();
}, [selectedCategory]);
const getCollection = async() => {
setIsLoading(true);
const index = 1;
const getThoughtsOneCategory = firebase.functions().httpsCallable('getThoughtsOneCategory');
return getThoughtsOneCategory({
index,
category: selectedCategory,
}).then((result) => {
setThoughts(result.data);
setIsLoading(false);
}).catch((err) => {
console.log(err);
});
};
and our results: https://imgur.com/a/koCa6Pr
any idea what we can do to make sure the data being displayed is the correct topic/category, and to stop the flickering?

making the call to firebase asynchronous fixed the issue:
const getThoughtsOneCategory = await firebase.functions().httpsCallable('getThoughtsOneCategory');

Related

React Native how do I make a Search Bar for a Flatlist?

I have been trying to create a search bar all day. I finally found this guide which seemed ok: https://blog.jscrambler.com/add-a-search-bar-using-hooks-and-flatlist-in-react-native/. I followed it through using my own API and I am not getting any errors exactly, but the code in this tutorial seems unfinished.
Here is what I have:
import React, { useEffect, useState } from 'react';
import { View, Text, FlatList, SafeAreaView, TextInput } from 'react-native';
import { Card, Header } from 'react-native-elements'
import { styles } from './styles.js';
import filter from 'lodash.filter';
const FormsScreen = ({navigation, route}) => {
const [isLoading, setIsLoading] = useState(false);
const [data, setData] = useState([]);
const [query, setQuery] = useState('');
const [fullData, setFullData] = useState([]);
//Fetch all users from database
useEffect(() =>{
setIsLoading(true);
fetch('http://10.0.2.2:5000/forms').then(response =>{
if(response.ok){
return response.json();
}
}).then(data => setFullData(data)).then(setIsLoading(false));
}, []);
function renderHeader() {
return (
<View
style={{
backgroundColor: '#fff',
padding: 10,
marginVertical: 10,
borderRadius: 20
}}
>
<TextInput
autoCapitalize="none"
autoCorrect={false}
clearButtonMode="always"
value={query}
onChangeText={queryText => handleSearch(queryText)}
placeholder="Search"
style={{ backgroundColor: '#fff', paddingHorizontal: 20 }}
/>
</View>
);
}
const handleSearch = text => {
const formattedQuery = text.toLowerCase();
const filteredData = filter(fullData, form => {
return contains(form, formattedQuery);
});
setData(filteredData);
setQuery(text);
};
const contains = ({ ID }, query) => {
console.log("ID was: "+ID);
console.log("Query was: "+query);
const id = ID;
console.log('id was: '+id);
if (id.toString().includes(query)) {
return true;
}
return false;
};
if (isLoading) {
return (
<View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
<ActivityIndicator size="large" color="#5500dc" />
</View>
);
}
else{
return (
<SafeAreaView>
<Header
leftComponent={{ icon: 'menu', color: '#fff' }}
centerComponent={{ text: 'Request Forms', style: { color: '#fff', fontSize: 25} }}
rightComponent={{ icon: 'home', color: '#fff' }}
/>
<FlatList
ListHeaderComponent={renderHeader}
keyExtractor={(item) => item.ID.toString() }
data={fullData}
renderItem={({item}) => (
<Card>
<Card.Title>{item.ID}</Card.Title>
<Card.Divider/>
<View style={styles.Container}>
<Text>{item.Comments}</Text>
{/* <Image source={require('./System apps/Media Manager/Gallery/AppPhotos/45e5cefd-7798-4fe9-88de-86a0a15b7b9f.jpg')} /> */}
<Text>{item.RoadName}</Text>
</View>
<View style={styles.ListContainer}>
<Text style={styles.LabelText}>Name</Text>
<Text style={styles.LabelText}>Phone</Text>
<Text style={styles.LabelText}>Email</Text>
</View>
<View style={styles.ListContainer}>
<Text style={styles.CardText}>{item.Name}</Text>
<Text style={styles.CardText}>{item.Phone}</Text>
<Text style={styles.CardText}>{item.Email}</Text>
</View>
</Card>
)}
/>
</SafeAreaView>
);
}
}
export default FormsScreen;
I have 2 main problems here.
1.) The tutorial had me initialize data and setData. setData is called and it looks to me like that is the final result after the search. The problem is that the author never actually used the variable data so I what do I do with it? Right now the the list is unaltered no matter what happens.
2.) I know he is using a different API so instead of filtering through First name, Last name, and Email I am only searching through ID. In this section of the tutorial:
const contains = ({ name, email }, query) => {
const { first, last } = name;
if (first.includes(query) || last.includes(query) || email.includes(query)) {
return true;
}
return false;
};
How does this code relate first and last to the first and last name values in the data? When I use this code but substitute name with ID and therefor first with id the value of query is correct (19 for example) but the value of ID is 2040 which is not the value I am looking for, but 2040 is the last ID in the database, or in other words the most recently entered row.
This is a sample of my data for reference:
Any help is greatly appreciated.
Please update
data={fullData}
to
data={query ? data : fullData} in flat list props. That should display your filtered data whenever search query updated.

Reset state after unmount screen - Hooks?

After getting data from API I set it to state, and render items in Flatlist,
when I select any item from it I manipulate data and add a new property to item object named as "toggle: true"
and it's works well when I select any item from list I add a border based on toggle,
But when I go back to previous screen then re open the lists screen I can see the border rendered around the items, although I reset the state when the unmounted screen
So what's the wrong I made here?
Code snippet
Data
export default {
...
services: [
{
id: 0,
name: 'nameS0',
logo:
'https://cdn2.iconfinder.com/data/icons/hotel-98/64/hair-dryer-tools-beauty-hairdressing-512.png',
price: 19.99,
},
],
employees: [
{
id: 0,
name: 'name0',
img:
'https://www.visualelementmedia.com/wp-content/uploads/2015/04/person-4-400x629.jpg',
},
...
],
};
const VendorProfile = ({navigation}) => {
const [services, setServices] = React.useState(null);
const [employees, setEmployees] = React.useState(null);
const [serviceSelected, setServiceSelected] = React.useState(null);
const [employeeSelected, setEmployeeSelected] = React.useState(null);
// For selected Item (services, employees)
const itemSelected = (data, id) => {
const updated = data.map((item) => {
item.toggle = false;
if (item.id === id) {
item.toggle = true;
data === services
? setServiceSelected(item)
: setEmployeeSelected(item);
}
return item;
});
data === services ? setServices(updated) : setEmployees(updated);
};
...
const renderEmployees = ({item}) => {
return (
<TouchableOpacity
onPress={() => itemSelected(employees, item.id)}
delayPressIn={0}
style={styles.employeeContainer}>
<EmployeePattern style={{alignSelf: 'center'}} />
<View style={styles.employeeLogo}>
<Image
source={{uri: item.img}}
style={[styles.imgStyle, {borderRadius: 25}]}
/>
</View>
<View style={{marginTop: 30}}>
<Text style={{textAlign: 'center'}}> {item.name}</Text>
</View>
<View style={{marginTop: 10, alignSelf: 'center'}}>
{item.toggle && <AntDesign name="check" size={25} color="#000" />} // here it's stuck after back and reopen the screen
</View>
</TouchableOpacity>
);
};
React.useEffect(() => {
setServices(VendorProfileData.services);
setEmployees(VendorProfileData.employees);
() => {
setServices(null);
setEmployees(null);
};
}, []);
return (
<View style={styles.container}>
<FlatList
data={services}
renderItem={renderServices}
horizontal
keyExtractor={(item) => item.id.toString()}
contentContainerStyle={{
justifyContent: 'space-between',
flexGrow: 1,
}}
/>
.....
</View>
);
};
Ok so after trying multiple times, i got it
change this
const updated = data.map((item) => {
to this
const updated = data.map((old) => {
let item = {...old};
and please make sure everything is working and we didn't break a thing :),
On your ItemSelected function you are passing the whole employees list, and going through it now thats fine, but when you changing one item inside this list without "recreating it" the reference to that item is still the same "because its an object" meaning that we are modifying the original item, and since we are doing so, the item keeps its old reference, best way to avoid that is to recreate the object,
hope this gives you an idea.

How to save State in React Native to Firebase

I am creating an app that allows a user to select multiple items from a Flatlist and the state changes once selected. However when I move away from that screen, all the selected items go back to the unselected state. How can use Firebase to save that state so it doesn't revert when I leave the screen? I am also open to alternative solutions to this issue.
Thank you for your time.
export default function StoreCatalogue({ navigation }) {
const { data, status } = useQuery('products', fetchProducts)
const [catalogueArray, setCatalogueArray] = useState([])
const [isSelected, setIsSelected] = useState([])
const [addCompare, setAddCompare] = useState(false)
const storeToDB = async (item) => {
if (!addCompare) {
await db.collection('users').doc(auth.currentUser.uid).collection('myProducts').doc(item.storeName + item.genName).set({
product_id: item.id,
product_genName: item.genName
})
} else {
await db.collection('users').doc(auth.currentUser.uid).collection('myProducts').doc(item.storeName + item.genName).delete()
}
}
const clickHandler = async (item) => {
setAddCompare(
addCompare ? false : true
)
if (isSelected.indexOf(item) > -1) {
let array = isSelected.filter(indexObj => {
if (indexObj == item) {
return false
}
return true
})
setIsSelected(array)
} else {
setIsSelected([
...isSelected, item
])
}
}
return (
<View style={styles.container}>
<FlatList
extraData={isSelected}
keyExtractor={(item) => item.id}
data={catalogueArray}
renderItem={({ item }) => (
<TouchableOpacity style={styles.btn} onPress={() => { storeToDB(item); clickHandler(item) }}>
<MaterialCommunityIcons name='plus-circle-outline' size={24} color={isSelected.indexOf(item) > -1 ? 'grey' : 'green'} />
<View style={{ position: 'absolute', bottom: 3 }}>
<Text style={{ fontSize: 10, textAlign: 'center', color: isSelected.indexOf(item) > -1 ? 'grey' : 'green' }}>{isSelected.indexOf(item) > -1 ? 'item \nAdded' : 'Add to\n Compare '}</Text>
</View>
</TouchableOpacity>
)}
/>
</View>
)
}
The problem is when you leave a screen the state gets reset to original, you can use Redux to store the state separately and on an event store the information on firebase once.
Firebase can be costly for this operation since every read and write will be chargeable.

getting data from api before page renders react-native hooks

thats it i need to get the values from the api before this one loads the slider this is how i call the api
useEffect(() => {
async function BCcontroller() {
const vCreationUser = 6;
const vSolicitudeId = 8;
const { data } = await ForceApi.post(`/ConsultBCController.php`, {vSolicitudeId, vCreationUser});
const values = data.terms;
setpterms(data.terms);
//console.log(values);
const [termA, termB, termC, termD] = values.split(',');
setvA(Number(termA));
setvB(Number(termB));
setvC(Number(termC));
setvD(Number(termD));
// console.log(values);
}
BCcontroller();
}, );
this is the slider code
<View style={{ alignItems: "stretch", justifyContent: "center" }}>
<Slider
maximumValue={D > 0 ? 4 : 3}
minimumValue={1}
step={1}
value={valuesFromApi.indexOf(Value)}
onValueChange={index => setValue(valuesFromApi[index])}
/>
<View style={styles.plazos}>
<Text style={styles.plazo1}>{A} meses</Text>
<Text style={styles.plazo2}>{B} meses</Text>
<Text style={styles.plazo3}>{C} meses</Text>
{D > 0 ? <Text style={styles.plazo3}>{D} meses</Text> : null}
</View>
<Text style={styles.slideText}>Su credito por: ${A}MXN</Text>
<Text style={styles.slideText}>Usted recibe: ${A}MXN</Text>
<Text style={styles.slideText}>A un plazo de: {sliderValue2} meses</Text>
<Text style={styles.PaymentText}>Su pago: ${A}.00 MXN</Text>
</View>
i thougt it was this way but the screen loads with a lot of undefineds and then it get the values of the api, so i want to have the values first and then render te components thanks for your help
You probably want your component to return null when there is no data yet. Only when the data is there, you can return the view+Slider.
Something like this:
const MyComponent = () => {
const [data, setDate] = useState();
useEffect(() => {
// ...
const { data } = await ForceApi.post(`/ConsultBCController.php`, {vSolicitudeId, vCreationUser});
setData(data)
// ...
}, [])
if (!data) return null;
return (
<View style={{ alignItems: "stretch", justifyContent: "center" }}>
// ...
</View>
)
}
When data is there, you call setData which will cause a rerender returning the View+Slider.
Of course the code above is incomplete and untested. It's intended to convey my intention. If it doesn't quite make sense, leave a comment and I'll try to enhance.

FlatList infinity scrolling on my code is not working

I am using RN for the development of an application, one of the components is a list of data, I perform the integration of a flat list to form the list...
<FlatList data={this.state.tickets}
keyExtractor={(item,index) => item._id + Math.random()}
refreshing={this.state.refreshing}
onRefresh={this.handleRefresh}
onEndReached={this.handleLoadMore}
onEndReachedThreshold={0.5}
ListFooterComponent={this.footerList}
renderItem={({item}) =>
<View style={styles.childOneFlat}>
<View style={styles.childTwoFlat}>
<TouchableOpacity style={styles.childThreeFlat}
onPress={() => {this.goToTask(item)}}>
<View style={styles.childFourFlat}>
<Text style={styles.childFiveFlat}>
{'Ticket N° '+item.taskId}</Text>
<Text style={styles.childSixFlat}>></Text>
</View>
</TouchableOpacity>
</View>
</View>}>
</FlatList>
Sorry for the bad indentation...
my methods :
handleRefresh = () => {
this.setState({
page:1,
refreshing:true
}, () => {
this.getTickets();
});
};
handleLoadMore = () => {
this.setState((prevStates,nextProps) => ({page: prevStates + 1,
loadingMore:true}), () => {this.getTickets();});
};
renderFooter = () => {
if (!this.state.loadingMore) return null;
return (
<View
style={{
position: 'relative',
width: width,
height: height,
paddingVertical: 20,
borderTopWidth: 1,
marginTop: 10,
marginBottom: 10,
borderColor: colors.veryLightPink
}}
>
<ActivityIndicator animating size="large" color='blue'/>
</View>
);
};
handleRefresh = () => {
this.setState(
{
page: 1,
refreshing: true
},
() => {
this._fetchAllBeers();
}
);
};
Someone may see the error that I could not find.
I would like to be able to incorporate infinity scrolling in the list, thanks to whoever answers from now...
Did you check whether your data prop is updating? this.state.tickets should always append the next items which are received from the this.getTickets(); API call instead of rewriting the whole array.

Categories