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

Issue with iframe's size not displaying correctly

<body> <script> document.write("<iframe id='theframe' src='http://www.website.com?testvr=" + testvr + " height='900' width='500'></iframe>"); </script> </body> The iframe is added, but ...

Cease the firing of ion-change until the values have been successfully loaded from storage

My settings page contains multiple ion-toggle's. There's an onChange method to update local storage when toggled. Standard procedure involves checking existing values in storage on page load and mapping them to the toggles using ngModel. <tab ...

Pass the initial value from a parent component to a child component in ReactJS without the need for state management

Initially, I have a parent Component A that calculates an initial value for its child Component B. The initial value is computed in the componentDidMount() of Component A and passed to B using props: <ComponentB initialValue={this.state.value} handleCha ...

What are the steps to successfully integrate Vuetify 2.3 or any other packages into a Vue 3 Project?

How can I properly register Vuetify in my main.js file without using Vue alias? After importing Vuetify, all of my components are hidden. Dependencies: "vue": "^3.0.0-rc.7", "vue-router": "^4.0.0-0", &quo ...

Ways to verify if one div in jQuery contains identical text to another div

I need help with a jQuery script to remove duplicate text in div elements Here's the requirement: If div1 contains the text "hi" and div2 also contains "hi", then div2 should be removed Below is my current code snippet: <script src="https:/ ...

having difficulty iterating through the data using map function

When attempting to use the map function in React Material UI to display an array of data in a select box, I encountered the error TypeError: Cannot read properties of undefined (reading 'map') while using the following code. Can anyone help me id ...

What is the best way to implement the Snackbar functionality within a class-based component?

My snackbar codes are not working as expected when I click the "confirm" button. I want the snackbar to appear after clicking the button. Most examples I've seen use functional components, so how can I get the Snackbar to work properly in a class comp ...

Invoking a function of a Redux-form React component

Is there a way to access the component method of a redux-form? I want my upload button to submit the form and also open the file select dialog if the user hasn't selected any file. Here is my code: UploadModal.js import React from 'react&apos ...

The constant issue persists with the NuxtJS store state variables continuously coming back as

I am facing an issue with the NuxtJs store where it keeps returning undefined. Even after looking at multiple similar questions, I haven't been able to find a solution. Here is my code snippet: import Vue from 'vue' import Vuex from 'vu ...

"Encountered an unexpected token when using an object parameter in a React function

I am facing an issue with a function I have implemented in React Native. const HandleConfirmApplication = async ( opts: { isInvite: boolean, confirmationCheckValues: () => any, confirmPopUp: () => any, loadingApply: () => any, ...

Is there a way to program custom key assignments for my calculator using JavaScript?

As a beginner in the world of coding and JavaScript, I decided to challenge myself by creating a calculator. It's been going smoothly up until this point: My inquiry is centered around incorporating keys into my calculator functionality. Currently, th ...

Toggle visibility of column data on button click in a Vue and Laravel application

I'm struggling with a table setup where each row contains a 'show details' button. Inside the table, there is another div stacked, and I want to display the table in the specific column when the button is clicked. However, I'm having di ...

Utilize the nest function in D3 to organize flat data with a parent key into a hierarchical structure

I'm searching for an elegant and efficient solution to transform my input data into a hierarchical structure using d3.js nest operator. Here is an example of the input data: [ {id: 1, name: "Peter"}, {id: 2, name: "Paul", manager: 1}, {id: 3, name: " ...

What steps should be taken to activate eslint caching?

I'm attempting to activate eslint caching by following the instructions in this section of the user guide The command I am using is npm run lint -- --cache=true, and the lint script simply executes a script that spawns esw (which itself runs eslint â ...

Is it possible to utilize a JS script generated within the body or head of an HTML file directly within CSS code?

As a beginner in webpage development, I have a query regarding the technical aspect. Is it possible to utilize variables from a JavaScript function, which is placed either in the head or body of an HTML file, directly in CSS code to make modifications such ...

Modifying the design of a website in real-time using the EXPRESS.js and NODE.js frameworks

I successfully set up a simple website using node.js and express.js by following this helpful tutorial. My express implementation is structured like this with a jade file for the web interface. // app.js var express = require('express'), r ...

Extracting information from a designated website using Python, including pages with search functionality and javascript features

Visit the website where you will find a search input box in html. Input a company name into the search box, select the first suggestion from the drop-down menu (like "Anglo American plc"), navigate to the URL containing information about that specific com ...

Puppeteer exhibiting unexpected behavior compared to the Developer Console

My goal is to extract the title of the page using Puppeteer from the following URL: Here's the code snippet I am working with: (async () => { const browser = await puppet.launch({ headless: true }); const page = a ...

In Vue, the sorting and filtering functionality is not always honored by JS-enhanced form components

Currently, I'm developing a simple to-do app using Vue. In this application, each item in a list generated by v-for consists of standard form fields like text inputs and checkboxes, as well as special form fields which are Vue components for WYSIWYG e ...

What is the best way to conceal a dropdown menu when the page first loads?

I have a dropdown menu that is displaying like this: <ul> <li class="dropdown open"> <a aria-expanded="true" href="#" class="dropdown-toggle waves-effect waves-button waves-classic" data-toggle="dropdown"> <spa ...