Flatlist is empty and array has values in it - react-native

I filled an array with querySnapshot but flatlist doesn't render anything
Tried to change renderItem code
constructor(props) {
super(props);
var rootref = firebase.firestore().collection("deneme");
var wholeData = []
rootref.get().then(function(querySnapshot){
querySnapshot.forEach(function(doc) {
wholeData.push(doc.data())
});
});
};
render() {
return (
<View>
<FlatList
data={this.wholeData}
renderItem={({item}) => <Text>{item.isim}, {item.soyisim}</Text>}
/>
</View>
);
};

You will have to use setState to notify the component that the data has changed. Change your code to do the following:
constructor(props) {
super(props);
this.state = {
data: []
};
var rootref = firebase.firestore().collection("deneme");
rootref.get().then(querySnapshot =>
const wholeData = querySnapshot.map(doc => doc.data()));
// notify your component that the data has changed
this.setState({
data: wholeData
})
};
render() {
return (
<View>
<FlatList
data={this.state.data} // get your data from the state
renderItem={({item}) => <Text>{item.isim}, {item.soyisim}</Text>}
/>
</View>
);
This way as soon as you have received the wholeData, the FlatList will update.

Related

how to pass props from flatlist to search?

I have my Main function in one file:
import Search from '../Components/Header';
function Main() {
return (
<View>
<Search />
<FlatList
data={this.state.data}
renderItem={renderItem}
keyExtractor={(item) => item.id}
style={{borderColor: 'black', borderWidth: 1, flexWrap: 'wrap'}}
/>
</View>
And Search class in another file:
const DATA = [
{
id: "1",
title: "Data",
}
];
const Item = ({ title }) => {
return (
<View>
<Text>{title}</Text>
</View>
);
};
const renderItem = ({ item }) => <Item title={item.title} />;
export default class Search extends Component {
constructor(props) {
super(props);
this.state = {
loading: false,
data: DATA,
error: null,
searchValue: "",
};
this.arrayholder = DATA;
};
searchFunction = (text) => {
const updatedData = this.arrayholder.filter((item) => {
const item_data = `${item.title.toUpperCase()})`;
const text_data = text.toUpperCase();
return item_data.indexOf(text_data) > -1;
});
this.setState({ data: updatedData, searchValue: text });
};
render() {
return (
<View style={Headerstyles.rectangle}>
<SearchBar
value={this.state.searchValue}
onChangeText={(text) => this.searchFunction(text)}
/>
</View>
);
}
}
So as I understand I should pass props from Flatlist to Search class, but I get an error TypeError: Cannot read property 'data' of undefined. I think it's not only about data and also renderItem and keyExtractor.
How can I do this?
The component Main does not contain a state called data. This state is defined in Search. I would create the state inside Main and pass the setter function to Search.
function Main() {
const [data, setData] = React.useState(DATA);
return (
<View>
<Search setData={setData} />
<FlatList
data={data}
renderItem={renderItem}
keyExtractor={(item) => item.id}
style={{borderColor: 'black', borderWidth: 1, flexWrap: 'wrap'}}
/>
</View>
)
}
Then, use the new props in Search as follows.
export default class Search extends Component {
constructor(props) {
super(props);
this.state = {
loading: false,
error: null,
searchValue: "",
};
this.arrayholder = DATA;
};
searchFunction = (text) => {
const updatedData = this.arrayholder.filter((item) => {
const item_data = `${item.title.toUpperCase()})`;
const text_data = text.toUpperCase();
return item_data.indexOf(text_data) > -1;
});
this.setState({ searchValue: text });
this.props.setData(updatedData);
};
render() {
return (
<View style={Headerstyles.rectangle}>
<SearchBar
value={this.state.searchValue}
onChangeText={(text) => this.searchFunction(text)}
/>
</View>
);
}
}

How display data with FlatList from useQuery?

Home Component :
export const Home: React.FC<Props> = (): any => {
const [recipesList, setRecipesList] = useState([] as Array<any>);
const { loading, error, data } = useQuery(GET_RECIPES);
useEffect(() => {
const getRecipes = () => {
if (error) {
return console.log(error);
}
if (loading) {
return console.log("LOADING =>", loading)
}
setRecipesList(data);
};
getRecipes();
}, [data]);
return (
<View style={styles.container}>
<Recipe recipesList={recipesList} />
</View>
);
};
Recipe Component :
export const Recipe: React.FC<Props> = (props: Props): any => {
const { recipesList } = props;
const displayRecipe = ({ item }: any) => {
console.log("RENDER ITEM")
return null;
};
return (
<View style={styles.container}>
<FlatList
data={recipesList}
extraData={recipesList}
numColumns={2}
renderItem={displayRecipe}
/>
</View>
);
};
Impossible to display data in the flatlist component, it never enters in the renderItem function no matter what I do. The recipesList is never empty when i log in.
You need to pass an array to the Flatlists data prop.
Try to change this line:
setRecipesList(data);
To this:
// I'm guessing that your query is named getRecipes
setRecipesList(data.getRecipes);

How do you use checkbox in map function in React Native?

My current code is like this.
export default class All extends React.Component {
constructor(props) {
super(props);
this.state = {
items: [],
checkedItems: new Map(),
};
this.handleChange = this.handleChange.bind(this);
}
handleChange(id) {
this.setState((prevState) => ({ checkedItems: prevState.checkedItems.set(id, true) }));
console.log(this.state.checkedItems);
}
async componentDidMount() {
const items = ...;
this.setState({ items });
}
render() {
const { items } = this.state;
return (
<Container>
<Content>
<View>
{items.map((item) => (
<View key={item.id}>
<Text>{item.name}</Text>
<View>
<CheckBox
checked={this.state.checkedItems.get(item.id)}
onPress={() => this.handleChange(item.id)}
/>
</View>
</View>
))}
</View>
</Content>
</Container>
);
}
}
I would like to know how to uncheck.
Also, when I firstly check, console.log() in handleChange() outputs Map {}.
Is it correct?
Or if you know better way bay to use checkbox in map function, plz tell me.
I would appreciate it if you could give me advices.

How to use swiper in react-native

Hi how can I have a swiper working in a Profil Component using the data from a Home component. I have a state in Home component where I stock data from a webservice.
class Accueil extends React.Component {
constructor(props) {
super(props);
this.state = {
refreshing: false,
latitude:null,
longitude:null,
dataSource:[],
error:null,
appState: AppState.currentState,
currentIndex: 0,
}
this.displayPosition = this.displayPosition.bind(this);
}
getData(){
fetch("SomeURL")
.then(res => res.json())
.then(result => {
return(
this.setState({
dataSource: result
}));
})
.catch(error => {
console.error(error)
})
}
render() {
return (
<SafeAreaView style={{ flex:1 }}>
<View style={styles.main_container}>
<FlatList style={styles.flatList}
data={this.state.dataSource}
extraData = {this.state}
keyExtractor={(item, index) => item.MembreId}
renderItem={(item) => <UserItem user={item} displayDetailForUser={this._displayDetailForUser} displaySwipe = {this._displaySwipe}/>}
numColumns={numColumns}
refreshing={this.state.refreshing}
onRefresh={this.handleRefresh} />
</View>
</SafeAreaView>
)
}
}
How can I use this.state.dataSource in Profil component in order to .map the swiper with the data ?
For passing values from one component to another, you can use the below code -
this.props.navigation.navigate('<Your Screen Name>', {
dataSource: this.state.dataSource
});
Now in your component you can access datastore just like below :
var tempDataSource = [...this.props.navigation.state.params.dataSource]
use it by accessing
this.props.navigation.state.params.dataSource this variable directly or you can save it in another variable just like above and
use it with your swiper.
I hope this helps, thanks :)

passing extraData to FlatList isn't working

I followed https://facebook.github.io/react-native/releases/next/docs/flatlist.html to make a FlatList and also passed this.state to extraData but still, once I delete an item, the item is still shown. I have also logged this.state to make sure the item is deleted and it indeed did. My code is below:
class DescriptionItem extends React.PureComponent {
render() {
return (
<TouchableOpacity
style={this.props.containerStyle}
onPress={(event) => {this.props.onPress(this.props.value)}}>
<Text style={this.props.style}>{this.props.value}</Text>
</TouchableOpacity>
)
}
}
export default class CardWorkDescriptionsList extends React.PureComponent {
constructor(props) {
super(props);
this.state = {
loading: false,
data: [],
error: null,
refreshing: false,
};
}
_notifyItemSelected(text) {
if(this.props.onItemSelected) {
this.props.onItemSelected(text)
}
}
_onItemSelected = (selectedItem) => {
var array = this.state.data;
var index = array.indexOf(selectedItem)
array.splice(index, 1);
console.log(array)
this.setState({data: array });
console.log("yeah",this.state.data)
this._notifyItemSelected(selectedItem);
}
makeRemoteRequest = () => {
//TODO: fetch data
this.setState({data: descriptionsFake})
}
componentDidMount() {
this.makeRemoteRequest();
}
render() {
return (
<View style={styles.cardLight}>
<FlatList
data={this.state.data}
extraData={this.state}
renderItem={(item) => (
<DescriptionItem
containerStyle={styles.itemContainer}
style={styles.content}
value={item.item}
onPress={(selectedItem)=>this._onItemSelected(selectedItem)}/>
)}
keyExtractor={item => item.substring(0,20)}
/>
</View>
);
}
}
Try extending React.Component instead of PureComponent