What is the best way to retrieve the most recent entry in a Firebase real-time database?

Utilizing Firebase's real-time database, I am updating values in a chart as they change. However, my struggle lies in retrieving only the most recent value added to the database.

While browsing through limitToLast and 'child_added' do not work together #1773, I attempted to implement some suggestions but couldn't get it to function properly.

Currently, this is what I have managed to achieve:

this.items = db.list('/items').valueChanges()
this.items.forEach(item => {
  this.data = item;
  this.add(this.data[this.data.length-1])
  console.log(this.data)
})

add(point: any) {
   this.chart.addPoint(point)
}

Realistically, I am aware that this approach is far from efficient.

Answer №1

According to the information found in the documentation:

list<T>(pathOrRef: PathReference, queryFn?: QueryFn): AngularFireList<T> {
 const ref = getRef(this.database, pathOrRef);
 let query: DatabaseQuery = ref;
 if(queryFn) {
   query = queryFn(ref);
 }
 return createListReference<T>(query, this);
}

The method list() allows for querying with a second parameter, as shown below:

this.items = db.list('/items', ref => ref.limitToLast(2)).valueChanges()

// Subscribe to changes
this.items.subscribe(lastItems =>{
  console.log(lastItems);  
});

The use of valueChanges() will provide an Observable that can be subscribed to in order to receive values.

For further details, please refer to:

https://github.com/angular/angularfire2/blob/master/docs/rtdb/querying-lists.md

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to troubleshoot the type of data being sent to the subscriber of an Angular observable?

I am new to the world of Angular-7, RxJS-6, and Visual Studio Code. Currently, I am facing a challenge with debugging an Observable that is being returned to a subscriber, resulting in a "TypeError" at runtime. It seems like this issue is not uncommon amon ...

Setting the selected <ion-option> in Ionic 3

Is it possible to programmatically set a default selected option in a dynamically created select menu using Ionic 3 and Angular? I want to make sure "Select State" is automatically chosen if the user hasn't made a selection yet, but I'm having t ...

The Express middleware type cannot be assigned as expected

I'm encountering an error where my first middleware is being red underlined. I can't figure out why it's only happening to the first one. Can anyone provide some guidance on this issue? I'm still quite new to TypeScript. Did I overloo ...

What causes branches coverage to appear haphazard?

I currently have 4 unit tests in place. const handleHttp = (method: 'POST' | 'GET' | 'PUT' | 'DELETE'): void => { const req = httpTestingController.expectOne(`${environment.apiUrl}test`); expect(req.request. ...

What is the method to define a function that strictly accepts a value of type T only if IsSomething<T> evaluates to true?

In my system, there is a complex generic type called IsUnique<T> that evaluates to either true or false based on the input type T: type IsUnique<T> = (/* ... */) ? true : false; Now I am looking to develop a function that takes an unique value ...

Tips for designing a custom TypeScript 5 property decorator

I have a decorator in TypeScript: const bindMethod = (method: any): PropertyDecorator => ((target: any, name?: PropertyKey): any => { if(name === undefined) { throw new Error('Bound decorator must be used with a property name.& ...

Discover the magic of integrating FeathersJS REST functionality within Angular with these simple steps

I've encountered a challenge while trying to make Feathers work in Angular with a Feathers REST server. It seems that no requests are being made. My Feathers server hosts the resource http://example.com/app/experiences which returns data in paginated ...

Material-UI: Error thrown when attempting to pass props to makeStyles in React due to missing property 'X' on type '{}'

Currently experimenting with Adapting based on props, you can find more information here import React from 'react'; import { makeStyles } from '@material-ui/core'; const useStyles = makeStyles({ // style rule foo: props => ( ...

Is it possible to utilize ngIf to reuse a component when encountering a 404 error? How can the error be captured?

In my app-routin.module.ts file, I have a root component named HomeComponent that I reuse for unknown routes. const routes: Routes = [ { path: '', component: PrimaryComponent, data: { breadcrumb: 'PRIMARY'}, children: [ { p ...

Encountered 'DatePickerProps<unknown>' error while attempting to develop a custom component using Material-UI and react-hook-form

Currently, I'm attempting to create a reusable component using MUI Datepicker and React Hook Form However, the parent component is throwing an error Type '{ control: Control<FieldValues, object>; name: string; }' is missing the follow ...

Converting a TypeScript class to a plain JavaScript object using class-transformer

I have a few instances of TypeScript classes in my Angular app that I need to save to Firebase. However, Firebase does not support custom classes, so I stumbled upon this library: https://github.com/typestack/class-transformer which seems to be a good fit ...

Error message encountered when trying to associate "can" with an ability instance within Types

Just copying example code from documentation import { createCanBoundTo } from '@casl/react'; import ability from './abilities'; export const Can = createCanBoundTo(ability); An error occurs on the last line: The exported variable & ...

Error: Azure AD B2C user login redirect URI is not valid

Currently working on setting up user login with Azure AD B2C. I have successfully created an App Registration in my B2C tenant and specified http://localhost:3000 as the redirect URI. However, when implementing it in my React app using the MSAL React libra ...

Troubleshooting Angular 6: Issues with Route Guards not functioning as expected

Striving to enhance frontend security by restricting access to specific IDs. The goal is to redirect anyone trying to access routes other than /login/:id to a page-not-found error message if not already logged in, but encountering some issues. Below are t ...

Guide on combining vendor CSS files in a React application using Webpack

Incorporating third-party libraries is an essential part of my project. For example, I have Mapbox GL installed via npm, which comes with CSS files needed for its functionality. The Mapbox GL CSS file can be found at mapbox-gl/dist/mapbox-gl.css in the no ...

Mapping URLs to objects in JavaScript, TypeScript, and Angular4

I have implemented a class called SearchFilter class SearchFilter { constructor(bucket: string, pin: number, qty: number, category: string) { } } When the user performs a search, I populate the filter i ...

Angular 13 implementation of a double-loop structure for fetching data from an API

I'm facing an issue with retrieving specific data fields label and svm from a JSON file. The desired fields are nested inside PORTFOLIO > REGROUPEMENT > ELEMENT. You can access the JSON file here. img(1) I've attempted to display the dat ...

There will be no further upgrades available for Angular CLI after version 1.6.0

Based on the latest information from npm, the current version of @angular/cli is v6.2.5. Upon running ng -v, the output shows: _ _ ____ _ ___ / \ _ __ __ _ _ _| | __ _ _ __ / ___| | |_ _| / △ &b ...

Using Angular, you can effortlessly inject elements into the editable div from any location on the page

Currently, I am working on developing an HTML interface that allows users to input text and send it as a notification to our mobile application. However, I am encountering challenges with the text and dynamically inserted elements using Angular 5; The te ...

Adjust the size of an event in the Angular Full Calendar with Chronofy, while utilizing constraints to control the drag and drop functionality

I'm currently in the process of developing an availability calendar for scheduling meetings during open times. If a time slot is unavailable, users should not be able to place an event there. While I have successfully implemented this feature, I am ...