While making a promise, an error occurred: TypeError - Unable to access the property '0' of null

I encountered an issue when trying to assign data from a function. The error appears in the console ((in promise) TypeError: Cannot read property '0'), but the data still shows on my application.

Here is the code:

<template>
                    <div class="row">
                        <div class="col-lg-12 bg-white" style="height: 100vh; overflow: scroll;">
                            <div class="wrap-content">
                                <h5 class="py-3 text-primary">QS</h5>

                                <div class="hero text-white px-3 py-4 mb-5">
                                    <p class="font-weight-300 font-12">Jumat, 23 April 2021 / 6 Syawal 1438</p>
                                    <h4>{{ jadwal_belum_terlewat[0].time }} WIB</h4>
                                    <p class="font-weight-300 font-14">Next prayer time</p>

                                    <p class="font-weight-300 font-12 mb-0"><i class="fas fa-map-marker-alt"></i> {{ this.address }}</p>
                                </div>
                            </div>
                        </div>
                    </div>
                </template>

                <script>
                    // import moment from 'moment'
                    import Alert from '../components/Alert'

                    export default {
                        name: 'PrayerSchedule',
                        components: {
                            Alert
                        },
                        data() {
                            return {
                                error_flag: false,
                                error_message: '',
                                lat: '',
                                long: '',
                                jadwal_belum_terlewat : null,
                                jadwal: [
                                    {
                                        name: 'FAJR',
                                        time: ''
                                    },
                                    {
                                        name: 'DHUHR',
                                        time: ''
                                    },
                                    {
                                        name: 'ASR',
                                        time: ''
                                    },
                                    {
                                        name: 'MAGHRIB',
                                        time: ''
                                    },
                                    {
                                        name: 'ISHA',
                                        time: ''
                                    }
                                ],
                                address: ''
                            }
                        },
                        methods: {
                            async getUserCoordinates() {
                                const check_permissions = await navigator.permissions.query({ name: 'geolocation' });
                                
                                if(check_permissions.state == 'granted') {
                                    this.error_flag = false;
                                    this.error_message = "";

                                    if (navigator.geolocation) {
                                        navigator.geolocation.getCurrentPosition(this.showPosition)

                                        this.error_flag = false;
                                        this.error_message = "";
                                    } else { 
                                        this.error_flag = true;
                                        this.error_message = "Your device does not support GPS";
                                    }
                                } else {
                                    this.error_flag = true;
                                    this.error_message = "Please enable GPS first";
                                }
                            },
                            showPosition(position) {
                                this.lat = position.coords.latitude;
                                this.long = position.coords.longitude;

                                this.getPrayerDetail();
                            },
                            async getPrayerDetail() {
                                const res = await fetch(`https://api.pray.zone/v2/times/today.json?latitude=${this.lat}&longitude=${this.long}`)

                                if(res.ok) {
                                    const data = await res.json();

                                    this.jadwal[0].time = data.results.datetime[0].times.Fajr;
                                    this.jadwal[1].time = data.results.datetime[0].times.Dhuhr;
                                    this.jadwal[2].time = data.results.datetime[0].times.Asr;
                                    this.jadwal[3].time = data.results.datetime[0].times.Maghrib;
                                    this.jadwal[4].time = data.results.datetime[0].times.Isha;

                                    this.jadwal_belum_terlewat = this.jadwal.filter((data) => new Date() < data.time);
                                }
                            },
                        },
                        created() {
                            this.getUserCoordinates()
                        }
                    }
                </script>

I am looking to populate the data for jadwal_belum_terlewat using this.jadwal.filter((data) => new Date() < data.time)

Your assistance in resolving this issue would be greatly appreciated. Thank you

Answer №1

Your verify_permissions function is in the state: prompt, which means the code will not enter the if block.

if (verify_permissions.state === "granted") { //<------------------- false
        this.error_flag = false;
        this.error_message = "";

        if (navigator.geolocation) {
          navigator.geolocation.getCurrentPosition(this.showLocation); //<--- why no parameter here? Your showLocation function expects one

          this.error_flag = false;
          this.error_message = "";
        } else {
          this.error_flag = true;
          this.error_message = "Your device does not support GPS";
        }
      } else // <---------- your landing here
        	this.error_flag = true;
            this.error_message = "Please enable GPS first"; 
}

After that, your code concludes.

By the way, there is no need to await a synchronous function like this:

                  // no need to await since navigator.permission is not async at all
const verify_permissions = await navigator.permissions.query({
        name: "geolocation",
      });

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 notify the user if the percentage entered is not a numeric value?

My role is to notify the user when the entered value exceeds the acceptable range: if (document.myForm.outputPercentage.value <= 0 || document.myForm.outputPercentage.value >= 100) { alert( "Please enter a percentage between 1 and 100 ...

Best Practices for Managing Asynchronous Updates in Angular Controllers

Let me explain my current setup -- I have a controller that utilizes a service to perform some tasks and then fetches data asynchronously. Right now, the data is returned after a timeout, but ideally it would involve more complex operations: This is how m ...

The functionality of the JavaScript click function is limited to a single execution

In my dropdown menu, I have a submit function that triggers whenever any children of the dropdown are clicked. However, I now need to exclude a specific li element from this function because it requires inserting a tracking ID in a popup iFrame. The code ...

implementing a smooth transition effect for image changes upon hover

I've been working on a React project where I created a card that changes its image when hovered over. I wanted to add a smoother transition effect to the image change using transition: opacity 0.25s ease-in-out;, but it doesn't seem to be working ...

What would be the counterpart of setLocale in Yup for the zod library?

How can I set default custom error messages for Zod validation? If I want to use i18n for error messages in Yup, I would do the following: import { t } from "i18next"; import * as yup from "yup"; import "./i18next"; yup.setL ...

Can I issue multiple SADD or ZADD commands in a single .sadd/.zadd call using ioredis?

I'm currently experimenting with ioredis for caching and indexing a substantial volume of data. However, my searches haven't yet yielded information on whether it supports performing multiple SADDs in one call. Can this be done, and if so, are t ...

Reset the checked state in React JSX to false by using a reset button

After attempting to reset selected radio buttons on this list, it seems like the change I made from {checked} to {user.checked} in input check is causing issues. This modification can be traced back to UserListElement.tsx In an effort to resolve this issu ...

Tips for Repurposing a React Table

I am in the process of developing my own react component library to be used across my entire application. At the moment, I have started with a table component which is currently undergoing testing. However, I am facing the challenge of calling the componen ...

What could be the reason behind the disappearance of text from the previously highlighted button in my calculator's "button grid" when I change the highlighted button?

Currently, I am in the midst of creating a tip calculator with a grid consisting of various percentage buttons. My main objective is to change the font and background color when any tip button is selected. Nevertheless, an issue has surfaced - whenever I h ...

What are the best ways to transfer information between functional components in a React application?

When working with React, data exchange between class-based components can be done using states and props in the following way: App.js import Name from './Name'; import React, { Component } from 'react' export class App extends Compo ...

Conceal elements and offspring in D3.js through the utilization of JavaScript or jQuery

I am currently customizing a fantastic force directed layout created by @eyaler (http://bl.ocks.org/eyaler/1058611) that offers multiple options. My goal is to conceal a specific node with its children using jQuery or D3 along with JavaScript, not directly ...

Eliminate apostrophes in a string by using regular expressions

Can someone help me with this word What is The Answer? I need to eliminate the space and apostrophe '. To remove spaces, should I use this method: data.text.replace(/ +/g, ""). But how can I remove the apostrophe? ...

Enhancing a Dropdown List with Jquery Using JSON Data

I am trying to populate a list using a JSON collection of objects. Here is the method that my action is returning: public ActionResult GetProductCategories() { var categories = _entities.ProductCategories.ToList(); var res ...

Error encountered in Vue Cli 3 when running Npm Build: Callback already triggered

Everything was running smoothly until this unexpected error popped up. I can execute npm run serve without any issues, but npm run build is a different story. Below is the detailed error log: 0 info it worked if it ends with ok 1 verbose cli [ 1 verbose c ...

Include new items in the li tag using JavaScript

Hello, I am looking to dynamically add elements to an LI element when a link is clicked. I have successfully added elements to a DIV using the following code snippet: I came across a similar question on Which "href" value should I use for JavaScript links ...

Learn the process of marking an option as selected within an Angular component

I have an Angular component that displays a question along with a dropdown menu (<select>) to choose from various answers. My goal is to programmatically set one of the options as selected based on certain parameters present in the application' ...

I am facing an issue where my Popover functions correctly when elements are added using HTML, but not when they are dynamically created

I'm currently working on a method to incorporate multiple popovers that have a similar appearance to the following: The screenshot of my first JsFiddle project (click to view) The initial progress I've made can be seen in my first JsFiddle, acc ...

The interval becomes congested due to the execution of two simultaneous Ajax calls

I have an Interval set to run a function every 3 seconds. intervalStepper = window.setInterval('intervalTick()','3000'); function intervalTick() { if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari ...

Bypass Security Check in Firefox

I am facing issues while trying to automate selenium on a website owned by a third party. When an authentication prompt like this appears in Firefox, Selenium fails: You can see a similar situation when clicking the Display Image button here Is there a ...

Javascript is experiencing a decrease in the variability of its content

I currently have multiple pages structured like this: <body> <table><tr><td align="center" width="100%"> --PAGE HTML-- </td></tr></table> </body> For a temporary period, I need to change the str ...