Setting up data in Firebase can be challenging due to its complex structure definition

https://i.stack.imgur.com/iclx7.png

UPDATE: In my firebase structure, I have made edits to the users collection by adding a special list called ListaFavorite. This list will contain all the favorite items that users add during their session. The issue I am facing is how to define the exact same structure in the original UserInterface file as in the firebase database.

The favoriteObj that I declared stores values from the item fields and sends them to firebase. However, I am unsure how to set the structure of favoriteObj since objects cannot be used in interfaces.

I hope this explanation clarifies my query. My goal is to match the structure below:

 const favoriteObj = {};
    favoriteObj[uniqID] = {
      favorite_title: favorite_title,
      favorite_description: favorite_description,
      favorite_image: favorite_image,
      favorite_tag: favorite_tag,
      favorite_stoc: favorite_stoc,
      favorite_reducere: favorite_reducere,
      favorite_price: favorite_price,
      favorite_userId: favorite_userId,
      isFavorite: true,
    };

with the User interface structure in firebase shown below:

export interface User {
  uid: string;
  email: string;
  displayName: string;
  photoURL: string;
  emailVerified: boolean;
  FavoriteID: string;
  SavedFavorite: boolean;
  AddCosID: string;
  SavedCos: boolean;
  ListaFavorite: ... // here i must pass the favoriteObj
}

Next, I need to include the function to update data:

SetUserData(user) {
    const userRef: AngularFirestoreDocument<any> = this.afStore.doc(
      `users/${user.uid}`
    );

    const userData: User = {
      uid: user.uid,
      email: user.email,
      displayName: user.displayName,
      photoURL: user.photoURL,
      emailVerified: user.emailVerified,
      FavoriteID: null,
      SavedFavorite: null,
      AddCosID: null,
      SavedCos: null,
      ListaFavorite : ...
    };
    return userRef.set(userData, {
      merge: true,
    });
  }

My aim is to designate the favorite objects within the current user interface and then retrieve all the objects for the logged-in user's favorite page. I am uncertain about how to pass the object there. Any guidance would be appreciated.

Answer №1

If you want to include an object in an interface, you can utilize nested interfaces. Start by creating an interface for favoriteObj:

interface FavoriteObj {
      favorite_title: string,
      favorite_description: string,
      favorite_image: string,
      ...
}

Next, nest it within the user interface using [key: string], also known as indexable types

export interface User {
  uid: string;
  email: string;
  displayName: string;
  photoURL: string;
  emailVerified: boolean;
  FavoriteID: string;
  SavedFavorite: boolean;
  AddCosID: string;
  SavedCos: boolean;
  ListaFavorite: {
       [key: string]: FavoriteObj
  }
}

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 steps can be taken to safeguard data while navigating within the Angular framework?

I am facing an issue with storing an array of items in a service (referred to as cart service) and displaying it in the component (cart.component.ts). The components bgview.component.ts and single.component.ts are involved in selecting individual items, wi ...

Exploring Angular 8 Route Paths

Working on an Angular 8 project, I encountered an issue with my code: src/app/helpers/auth.guard.ts import { AuthenticationService } from '@app/services'; The AuthenticationService ts file is located at: src/app/services/authentication.servic ...

Ways to dynamically update a Vuetify 3 element's placeholder text?

Here is the code snippet from my component.vue file: <template> <v-text-field name="Foo" :label="$t('foo')" type="text" hint="This is a hint" persistent-hint >& ...

Issue with Angular ngStyle toggle functionality not activating

I'm having an issue with toggling my navbar visibility on click of an image. It works the first time but not after that. Can anyone provide some assistance? Link to Code <img id="project-avatar" (click)="toggleNavbar()" width=20, height=20 style= ...

Compilation issues encountered while running TypeScript in Dockerfile

I am encountering an issue with my Dockerfile during the TypeScript compilation step. Below is the snippet of code where it fails: FROM node:12 WORKDIR /usr/src/app # SETUP COPY package.json . COPY tsconfig.json . COPY src . RUN npm install -g yarn@^1. ...

Issue with VS2017RC: TypeScript fails to produce JavaScript files

After updating to VS 2017, I noticed that modifications made to a typescript file no longer result in the generation of any javascript code, despite receiving a message indicating "outputs generated successfully" on the lower bar. I tested this issue on t ...

Exploring ways to destructure the useContext hook with a null default value in your Typescript code

Initially, I set up a context with a null value and now I am trying to access it in another component. However, when I destructure it to retrieve the variables from the context, I encounter a TypeScript error: Property 'users' does not exist on ...

An array devoid of elements may still hold significance

I have a specific function structure as follows: public returnData(): { points: Array<{ x: number, y: number }>, pointsCount: Array<number> } { return { points: [{x: 0, y: 1},{x: 1, y: 2 }], pointsCount: [1, 2, 3, 4] } ...

Ways to access configuration settings from a config.ts file during program execution

The contents of my config.ts file are shown below: import someConfig from './someConfigModel'; const config = { token: process.env.API_TOKEN, projectId: 'sample', buildId: process.env.BUILD_ID, }; export default config as someCo ...

Failed to import due to an error from the downloaded dependency

I'm encountering an import error in the @react-three module of my downloaded package. ./node_modules/@react-three/drei/node_modules/troika-three-text/dist/troika-three-text.esm.js Attempted import error: 'webgl-sdf-generator' does not cont ...

Firebase is not updating the number

Having just started with Firebase, I have been following all the guidelines for web Firebase auth. I have successfully managed to login, log out, and update all data except for the phone number. Despite receiving a success message in the console, my phone ...

Calculate the sum of multiple user-selected items in an array to display the total (using Angular)

Within my project, specifically in summary.component.ts, I have two arrays that are interdependent: state: State[] city: City[] selection: number[] = number The state.ts class looks like this: id: number name: string And the city.ts class is defined as f ...

Discover the solution for seamless integration of TypeScript with the novel `exports` and `main` field

I am currently utilizing Node.js version 16.10.0 along with TypeScript 4.5.5. As part of my development process, I am in the midst of publishing a library and have implemented the following configuration: "main": "./dist/index.js", ...

Expanding the capabilities of generic functions in TypeScript using type variables

When working with generics in TypeScript, it is often beneficial for a function that accepts generically-typed arguments to have knowledge of the type. There exists a standard approach to achieve this using named functions: interface TestInterface<T> ...

Struggling to delete event listeners in TypeScript using object-oriented programming with JavaScript

After researching the issue, I have discovered that the onMouseUp event is being fired but it is not removing the EventListeners. Many individuals facing a similar problem fail to remove the same function they added initially. Upon reading information fr ...

Encountered an error when incorporating nguniversal/express-engine into an Angular project: "Unable to locate the BrowserModule import in /src/app/app.module.ts"

One of the initial questions Purpose The main aim is to integrate SSR into my Angular project using ng add @nguniversal/express-engine --clientProject [name] (to enable dynamic prerendering of meta tags). Expected Outcome I anticipated the command to run ...

A guide to implementing localStorage in TypeScript

When attempting to assign the object item to Product using this code: localStorage.setItem("Product", JSON.stringify(item)) The JSON string of item is not properly assigned to Product. Is there a solution to this issue? ...

The proper method for retrieving FormData using SyntheticEvent

I recently implemented a solution to submit form data using React forms with the onSubmit event handler. I passed the SyntheticBaseEvent object to a function called handleSubmit where I manually extracted its values. I have identified the specific data I n ...

What is the best way to send props (or a comparable value) to the {children} component within RootLayout when using the app router in Next.js

As I work on updating an e-commerce website's shopping cart to Next.js 13+, I refer back to an old tutorial for guidance. In the previous version of the tutorial, the _app.ts file utilized page routing with the following code snippet: return ( < ...

Understanding the Typescript Type for a JSON Schema Object

When working with JSON-schema objects in typescript, is there a specific type that should be associated with them? I currently have a method within my class that validates whether its members adhere to the dynamic json schema schema. This is how I am doing ...