Encountering the issue of receiving undefined values for both error and url during the utilization

I'm currently working on a file called createCheckoutSession.ts:

import { db } from '../firebase/firebaseInit';
import { collection, addDoc, onSnapshot } from 'firebase/firestore';
import { User } from 'firebase/auth';

export async function createCheckoutSession(user: User) {

    console.log('clicked')
    

    const docRef = await addDoc(collection(db, `users/${user?.uid}/checkout_sessions`), {
        price: 'price_1Lb3hiKi0c1bV0RosKIhQ699',
        success_url: `http://localhost:3000/success`,
        cancel_url: `http://localhost:3000/cancel`,
    });

    console.log(docRef)

    onSnapshot(docRef, (snap) => {
        console.log('dsfdsfdf')
        const { error, url } = snap.data();
        console.log(error, 'snap')
            if (error) {
                // Show an error to your customer and
                // inspect your Cloud Function logs in the Firebase console.
                alert(`An error occured: ${error.message}`);
            }
            if (url) {
                // We have a Stripe Checkout URL, let's redirect.
                window.location.assign(url);
            }
        });
}

When using vscode, I encountered an error message for this line of code:

const { error, url } = snap.data();
:

Property 'error' does not exist on type 'DocumentData | undefined'.ts(2339)

An error was also displayed in the console:

Uncaught (in promise) FirebaseError: Missing or insufficient permissions.

Here are my security rules that might be related to the issue:

rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    match /users/{uid} {
      allow read, write: if request.auth.uid == uid;

      match /checkout_sessions/{id} {
        allow read, write: if request.auth.uid == uid;
      }
      match /subscriptions/{id} {
        allow read: if request.auth.uid == uid;
      }
    }

    match /products/{id} {
      allow read: if true;

      match /prices/{id} {
        allow read: if true;
      }

      match /tax_rates/{id} {
        allow read: if true;
      }
    }
  }
}

I am receiving undefined values for both error and url. Any suggestions on how to resolve this issue?

Answer №1

When the document does not exist, snap.data() will return undefined, resulting in an error when trying to read properties of undefined. To avoid this issue, it is important to check if the document exists before attempting to access its data:

onSnapshot(docRef, snap => {
  console.log("In onSnapshot");

  // Check if the document exists
  if (snap.exists()) {
    const { name, error } = snap.data(); // This will always have a defined value
  } else {
    console.log("Document does not exist");
  }
});

To ensure that users are able to read and write their own data, make sure to adjust the security rules accordingly. You can grant access to specific documents based on user authentication like so:

rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    match /users/{userId}/{data=**} {
        allow read, write: if request.auth.uid == userId;
    }
  }
}

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

Controller encounters a error when requiring a module

Struggling to set up Stripe for my app, I've encountered some issues with the module implementation. Typically, I would require a module at the top of the file to use it. However, in the paymentCtrl file, when I do this, it doesn't work and I rec ...

Incorporate an Array of Objects into the UseState hook with an initial value

I have encountered an issue with the following error message: "Error: Objects are not valid as a React child (found: object with keys {fzfvhv76576, user }). If you meant to render a collection of children, use an array instead." I have been attem ...

Guide to customizing CSS styles within a div element using TypeScript code in a Leaflet legend

I'm struggling to add a legend to my map using Angular 5 and typescript. I need help with setting CSS styles for the values (grades) that are displayed on the legend. Can someone guide me on where to put the styles? TS: createLegend() { let lege ...

Tips for displaying dynamic images using the combination of the base URL and file name in an *ngFor loop

I have a base URL which is http://www.example.com, and the file names are coming from an API stored in the dataSource array as shown below: [ { "bid": "2", "bnam": "ChickenChilli", "adds": "nsnnsnw, nnsnsnsn", "pdap": " ...

Merging Two JSON Objects into a Single Object Using Angular 4-6

Two JSONs are available: The first one (with a length of 200): {date_end: "2099-12-31", id: "2341"} {date_end: "2099-12-31" id: "2342"} ... The second one (length 200): {type: "free", discount:"none", warranty: "yes"} {type: "free", discount:"none", ...

Function outcome influenced by variable type

I am working with an enum that represents different types of nodes in a tree structure. enum MyEnum { 'A' = 'A', 'B' = 'B', 'C' = 'C', // ... } Each node in the tree has specific types of ...

Only one choice for discriminated unions in react props

Looking to create a typescript type for react component props, specifically a basic button that can accept either an icon prop or a text prop, but not both. My initial attempt with a discriminated union didn't quite produce the desired outcome: inter ...

The module cannot be located: Unable to find '../typings' in '/vercel/path0/pages'

Having trouble deploying my Next.js website through Vercel. It seems to be stuck at this stage. Can someone assist me, please? I've attempted deleting the node_modules folder and package-lock.json, then running npm install again, but unfortunately it ...

Accessing the state from a child functional component and then adding it to an array of objects in the parent component

I'm facing a challenge with a parent component that needs to manage the data of its child components stored in an array of objects. My goal is to add new child components and maintain their information within the parent's state as an array of obj ...

What are the solutions for handling undefined data within the scope of Typescript?

I am encountering an issue with my ngOnInit() method. The method fills a data list at the beginning and contains two different logic branches depending on whether there is a query param present (navigating back to the page) or it's the first opening o ...

Unlocking the power of global JavaScript variables within an Angular 2 component

Below, you will find a global JavaScript variable that is defined. Note that @Url is an ASP.Net MVC html helper and it will be converted to a string value: <script> var rootVar = '@Url.Action("Index","Home",new { Area = ""}, null)'; Sy ...

Troubleshooting connectivity problems: SocketIO integration with microservices on a Kubernetes platform

I have organized my system using microservices architecture, with separate services for client interactions, orders, payments, and more. Each of these services runs on its own express server. Now, I am looking to integrate real-time feedback functionality ...

How come my counter is still at 0 even though I incremented it within the loop?

Within my HTML file, the code snippet below is present: <div id="userCount" class="number count-to" data-from="0" data-to="" data-speed="1000" data-fresh-interval="20"></div> In my Ja ...

Uniting 2 streams to create a single observable

I am in the process of merging 2 different Observables. The first Observable contains a ShoppingCart class, while the second one holds a list of ShoppingItems. My goal is to map the Observable with shopping cart items (Observable<ShoppingItems) to the i ...

What is the best way to handle updating an npm package that is not the desired or correct version?

I've been experimenting with querying data on Firebase using querying lists. My attempt to implement functionality similar to the documentation resulted in this code snippet: getMatchesFiltered(matchId: string, filter: string, sortDirection: string, ...

Verification for collaborative element

I am currently working on creating a shared component for file uploads that can be reused whenever necessary. Interestingly, when I include the file upload code in the same HTML as the form, the validation functions properly. However, if I extract it into ...

Experience the dynamic live preview feature of Sanity integrated with NextJS 13

I am facing an issue with checking if preview mode is activated on my website. While following a YouTube tutorial, I realized that the instructions may be outdated with the latest NextJS update. This was the code snippet I was originally working with to ...

The specified type '{ rippleColor: any; }' cannot be assigned to type 'ColorValue | null | undefined'

I've been diving into learning reactnative (expo) with typescript, but I've hit a roadblock. TypeScript keeps showing me the error message Type '{ rippleColor: any; }' is not assignable to type 'ColorValue | null | undefined' ...

Installation of Axios on Firebase Functions with Node.js 14 encountered errors

While working with Firebase Functions, I encountered an issue when attempting to install and use axios. Despite using npm install to add the package as shown below, the installation failed without any clear indication of what went wrong during runtime. Co ...

Notify user before exiting the page if there is an unsaved form using TypeScript

I am working on a script that handles unsaved text inputs. Here is the code for the script: export class Unsave { public static unsave_check(): void { let unsaved = false; $(":input").change(function(){ unsaved = true; ...