Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
564 views
in Technique[技术] by (71.8m points)

reactjs - Data obtained from Firebase Realtime Database in React Native using Hooks is not displayed on the screen

I started using Hooks in React Native recently and I'm trying to get the data from Firebase Realtime Database and render it in FlatList. The data is being displayed on the console, in object format, but it is not working, it is not being rendered on the screen. What am I doing wrong? How do I make it work correctly?

My code:

import React, { useState, useEffect } from "react";
import { StyleSheet, View, Text, FlatList } from 'react-native';

import firebase from '@firebase/app';
import '@firebase/database';

export default function QuestList({ navigation }) {
  const title = navigation.getParam('title');
  const [data, setData] = useState([]);

  useEffect(() => {
      const db = firebase.database();
      db.ref('/questionnaires/')
        .on('value', snapshot => {
          console.log(snapshot.val());
          const data = snapshot.val();
        });
  }, []);

  return (<FlatList 
    data={data}
    renderItem={
      ({ item, index }) => (<View>
        <Text index={index}>{item.title}</Text>
      </View>)
    }
    keyExtractor={item=>item.id}
    numColumns={2}
    showsVerticalScrollIndicator={false}
    />
  );
}
question from:https://stackoverflow.com/questions/65649985/data-obtained-from-firebase-realtime-database-in-react-native-using-hooks-is-not

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You're probably missing a setData call in your useEffect

useEffect(() => {
  const db = firebase.database();
  db.ref('/questionnaires/')
    .on('value', snapshot => {
      const response = snapshot.val();
      setData(response);
    });
}, []);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...