Firebase allows for the updating of an object within a nested array

Within Firestore, I have a Document that includes a property named "items" which is of type array. This array consists of ShoppingItem objects with the specified structure:

export class ShoppingItem {
 id?: string; 
 name: string;
 checked = false;
}

To further elaborate, here is the structure of the document:

export interface ShoppingList {
 id: string;
 name?: string;
 items: ShoppingItem[]; // <-- This is the array property I am modifying
}  

Users can modify the checked property of an object through the UI, and I intend to sync these changes with the database. According to Firebase documentation, we can use arrayRemove/arrayUnion to add or remove array elements atomically.

Questioning whether it's necessary to remove the old object and add the new one in nested promises each time for updating an existing item, like demonstrated below, or if there might be a more elegant solution:

updateItem(listId: string, item: ShoppingItem) {
  const docRef = this.db.collection("list").doc(listId)

  return docref.update({ items: firestore.FieldValue.arrayRemove(item) })
    .then(() => {
    {
      docRef.update({ items: firestore.FieldValue.arrayUnion(item) });
    }
  });
}

A known downside of removing and adding the item within the array results in a noticeable flickering effect in the UI for the updated element.

Answer №1

Unfortunately, there is currently no method to individually update a particular field within an array of objects. Employing (arrayRemove/arrayUnion) remains the sole viable remedy in this situation.

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

The JavaScript variable assigned from the MySQL query through an Express API is returning as undefined, indicating that the promise is not resolving to

Hey there, I'm trying to assign the result of a MYSQL query to a JS variable so that I can use it multiple times. However, whenever I try to do this, I end up receiving an empty array. Can anyone point out what might be causing this issue in my code? ...

Issue with Repeated String Test in JavaScript: Single Failure Detected

Currently tackling the Repeated String Challenge on HackerRank. The challenge description goes as follows: A string, denoted by s, consisting of lowercase English letters is repeated infinitely. With an integer, n, the goal is to determine and output the ...

Having trouble retrieving the .html() content from the <label> element

Check out the code below: $('.size_click').click(function () { $(this).closest('span').toggleClass('active_size'); $('.selected_sizes').append($(this).closest('label').html()); }); There are multiple ...

What is the best way to transfer information to a different component using Vue router?

At the moment, I have a component that is displayed on the page. When I check the this.$router variable inside this component, I notice that the full path property is '/hello/reports?report=3849534583957' and the path property is '/hello/rep ...

Creating a NgFor loop in Angular 8 to display a dropdown menu styled using Material

I'm currently facing an issue with incorporating a Materialize dropdown within a dynamically generated table using *ngFor. The dropdown does not display when placed inside the table, however, it works perfectly fine when placed outside. <p>User ...

Angular's custom reactive form validator fails to function as intended

Struggling to incorporate a customized angular validator to check for date ranges. The validator is functioning correctly and throwing a validation error. However, the issue lies in the fact that nothing is being displayed on the client side - there are n ...

Convert the value of a Javascript variable into a PHP variable

I am feeling confused about how to pass JavaScript variables to PHP variables. Currently, I have a PHP session named example_survey and three buttons with jQuery attributes. When a button is clicked, it triggers a jQuery click event and passes the attribut ...

JavaScript event listener on the "change" event only triggers when changed manually [CodePen]

Check out this jsFiddle I created with all the data and information related to the issue. It should make it easier to understand what's happening: Take a look here: http://jsfiddle.net/lukinhasb/GuZq2/ $("#estado").val(unescape(resultadoCEP["uf"])); ...

Ways to solely cache spa.html using networkfirst or ways to set up offline mode with server-side rendering (SSR)

I am facing an issue with my application that has server-side rendering. It seems like the page always displays correctly when there is an internet connection. However, I am unsure how to make Workbox serve spa.html only when there is no network available. ...

What is the best way to split an input field into distinct fields for display on the screen?

Take a look at this image: https://i.stack.imgur.com/LoVqe.png I am interested in creating a design similar to the one shown in the image, where a 4 digit one-time password (OTP) is entered by the user. Currently, I have achieved this by using 4 separate ...

"Utilizing the power of Node.js to perform SQL queries with

I'm having trouble with this SQL query that uses INNER JOIN. The query is returning an error. connection.query("SELECT caracavis.caracname FROM caracavis WHERE firstcaturl ='" + req.body[0].firstcatname + "' AND secondcaturl = '" + r ...

Encountering a Node Js post handling error with the message "Cannot GET /url

This is my ejs file titled Post_handling.ejs: <!DOCTYPE html> <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <title>POST-Handling Page</title> </head> <body& ...

Can you explain the meaning of the ?. operator in JavaScript?

While using react-hook-form, I encountered the ?. operator. Can you explain its meaning? Here's an example of how it works: <span>{errors?.name?.message}</span> The errors variable is obtained from useForm() by destructuring, as shown bel ...

What are the steps involved in converting a MERN application into a desktop application?

As a beginner in front-end application development, I recently created a MERN application in React with separate frontend and backend parts. Everything is working smoothly, but now I want to convert it into a desktop application that can run independently ...

Which approach yields better performance: setting all dom events simultaneously, or incrementally?

Is it more effective to attach event listeners permanently or only when needed? For example, consider a scenario where you have a dropdown menu in your HTML that opens when clicked. Within this menu, there is a close button that closes the menu upon click ...

Error in Laravel Mix Vuejs component: Syntax problem detected in <template />

My development environment involves Windows 10 OS and I have created a Laravel 8 project integrated with VueJs. However, when I try to access the file ./components/app.vue, it returns a SyntaxError: Unexpected token (1:0) The content of the app.vue file i ...

Dealing with Uncaught Type Errors in the Fixed Data Table

I am attempting to implement a fixed data table using the following code snippet. var MyCompi = React.createClass({ getInitialState: function() { return { rows : [ {"id":1,"first_name":"William","last_name":"Elliott","email":"<a ...

What is the best way to enforce constraints on three keys when validating an object using Joi?

Currently experimenting with Joi for object validation. Able to validate objects with constraints on two keys using any.when(). Now looking to implement validation with constraints on three keys, for example: var object = { dynamicPrize: false, ...

What could be causing this JavaScript if statement to malfunction?

I found myself with some free time and decided to create a basic API using JavaScript. What I thought would be simple turned into a frustrating mistake. Oddly enough, my if/else statement isn't working correctly - it only executes the code within the ...

Exploring the depths of Javascript objects using Typescript

If I have this specific dataset: data = { result: [ { id: '001', name: 'Caio B', address: { address: 'sau paulo', city: 'sao paulo', ...