Tushar Sharma
Tushar Sharma

Reputation: 15

Sort Data Using Time Value in Realtime Database using React-js

I am trying to sort my Firebase Data based on the Time it was created on such that the entry created last should come on the top. Below is my code for the same,

import React, { useEffect, useState } from 'react'
import fire from './fire1';
export const Weight = () => {

const[input, setInput] = useState("")
const[weightList, setWeightList] = useState("")
const handleOnSubmit = () =>{
    const dataRef = fire.database().ref('Tushar');
    const data = ({
        input,
        time : new Date().toLocaleTimeString()
    });
    dataRef.push(data)
    console.log(dataRef.orderBy('currTime').get())
}
useEffect(()=>{
    
    const dataRef =  fire.database().ref('Tushar');
    dataRef.on('value', (snapshot)=>{
        var weight = (snapshot.val())
        var weightList = []
        for (let id in weight){
            weightList.push(weight[id])
        }
        setWeightList(weightList)
        
    })
},[])

return (
    <div>
            <input
            type = "text"
            placeholder = "Enter Your Weight"
            value = {input}
            onChange = {(e)=> setInput(e.target.value)}
            />
            <button onClick = {handleOnSubmit} >Submit</button>
        {weightList? weightList.map((val, index) =>{
            return(
                <div key = {index} >
            <h1>{val.input}</h1>
            <i>{val.time}</i>    
                </div>
            )
        }): "" }
    </div>
)
}

When I am trying to use the OrderBy() Function It is showing the following error.

TypeError: dataRef.orderBy is not a function

Do let me know if I am committing any error or missing some piece of information.

Upvotes: 0

Views: 426

Answers (1)

50_Seconds _Of_Coding
50_Seconds _Of_Coding

Reputation: 512

Firebase real time database documentation

read the data section

The query you are trying to use is of firebase firestore database and not realtime database,

These are the queries for realtime database

orderByChild()  : Order results by the value of a specified child key or nested child path.
orderByKey()    : Order results by child keys.
orderByValue()  : Order results by child values.

Upvotes: 1

Related Questions