Home > front end >  Render Item in Agenda using database data - React Native
Render Item in Agenda using database data - React Native

Time:08-24

I'm trying to show the items I get from my database in the calendar, everything is working fine (maybe not), but in short I got the data from the database with an array and then I converted it to an object (because the calendar only accepts objects), but it doesn't show anything and it doesn't give an error either


import React, { useEffect, useState } from 'react'
import { StyleSheet, View, Text } from 'react-native'
import { LocaleConfig, Agenda } from 'react-native-calendars'
import DateTimePicker from 'react-native-modal-datetime-picker';

import { getAuth } from 'firebase/auth';
import { getDatabase, ref, onValue, set, push, get, child } from 'firebase/database';


const Calendario = () => {
 const dbRef = ref(getDatabase());
 const data = []
 var obj = {}

// getting data from the database

  useEffect(() => {
    getInDB()
  } ,[])

  const getInDB = () => {
    get(child(dbRef, 'users/'   app.currentUser.uid)).then((snapshot) => {
        snapshot.forEach(childsnap => {
          let dateD = childsnap.child("date").val()
          let titleD = childsnap.child("title").val()
          let dtsD = childsnap.child("details").val()

          // "yyyy-MM-dd": [{any: "whatever", any2: "whatever"}],
          data.push({
            [dateD] : [{ title: titleD, details: dtsD }],
          });

        })
        obj = Object.assign({}, ...data)
        console.log(obj)
    })
  }

  const renderItem = (item) => {
    return(
        <View style={styles.itemContainer}>
            <Text style={styles.textInf}>{item.title}</Text>
            <Text style={styles.textInf}>{item.details}</Text>
        </View>
    )
  }

 return (
  <>
   <Agenda
   items={obj}
   renderEmptyDate={() => {
    return <View />;
   }}
   renderEmptyData={() => {
    return <View />;
   }}
   selected={new Date()}
   minDate={null}
   renderItem={renderItem}
   markingType="custom"
   />
  </>
}

CodePudding user response:

You need to use state and set it or otherwise your component will not be rerendered with the new data.

Furthermore, the Agenda component expects an object. By using data as an array and the spread operator, we won't get the desired result.

You can implement this correctly as follows.

...
const [obj, setObj] = useState({});
...

const getInDB = () => {
    get(child(dbRef, 'users/'   app.currentUser.uid)).then((snapshot) => {
        const temp = {}
        snapshot.forEach(childsnap => {
          let dateD = childsnap.child("date").val()
          let titleD = childsnap.child("title").val()
          let dtsD = childsnap.child("details").val()

          Object.assign(temp, {dateD: [{ title: titleD, details: dtsD }]})

        })
        setObj(temp)
    })
  }

I have implemented a little snack.

  • Related