MCPcopy Index your code
hub / github.com/FirebaseExtended/reactfire / AnimalsList

Function AnimalsList

example/withSuspense/RealtimeDatabase.tsx:30–81  ·  view source on GitHub ↗
()

Source from the content-addressed store, hash-verified

28};
29
30const AnimalsList = () => {
31 const database = useDatabase();
32 const animalsRef = ref(database, 'animals');
33 const animalsQuery = query(animalsRef, orderByChild('commonName'));
34 const { data: animals } = useDatabaseListData<{ commonName: string; id: string }>(animalsQuery, {
35 idField: 'id',
36 });
37
38 const addAnimal = () => {
39 const possibleAnimals = ['Dog', 'Cat', 'Iguana', 'Zebra'];
40 const selectedAnimal = possibleAnimals[Math.floor(Math.random() * possibleAnimals.length)];
41 const newRef = push(animalsRef);
42 set(newRef, { commonName: selectedAnimal });
43 };
44
45 if (!animals) {
46 return <span>no animals found</span>;
47 }
48
49 return (
50 <>
51 <div className="h-20 overflow-x-scroll shadow-inner m-2 border border-black">
52 <ul>
53 {animals.map((animal) => (
54 <li key={animal.id as string}>{animal.commonName as string}</li>
55 ))}
56 </ul>
57 </div>
58 <ul>
59 {Array.from(
60 animals.reduce((animalCountMap, animal) => {
61 const currentCount = animalCountMap.get(animal.commonName) ?? 0;
62 return animalCountMap.set(animal.commonName, currentCount + 1);
63 }, new Map<string, number>())
64 ).map((animalStat: [string, number]) => {
65 const [animalName, animalCount] = animalStat;
66 return (
67 <li key={animalName}>
68 {animalName}: {animalCount}
69 </li>
70 );
71 })}
72 </ul>
73 <WideButton
74 label="Add Animal"
75 onClick={() => {
76 addAnimal();
77 }}
78 />
79 </>
80 );
81};
82
83export const RealtimeDatabase = () => {
84 const firebaseApp = useFirebaseApp();

Callers

nothing calls this directly

Calls 3

useDatabaseFunction · 0.85
useDatabaseListDataFunction · 0.85
addAnimalFunction · 0.70

Tested by

no test coverage detected