mardi 30 mars 2021

Bundled Javascript r is null

It's been several days this error accured. I'm trying to build simple website which can interact with covid-19 API to get data. I'm done with the html and css, and also i managed to write JS code to retrieve data from API. At first, all i do is write the html, and using JS as embedded script (inside tag).

Everythings work fine, and as i wanted to. But, problem happen when i try to separate html, css and JS using webpack and webcomponent. The main problem is the html and css works fine, but lost all JS effect. All event listener simply can't work.

this is the files which i think causing problem:

./src/index.js (webpack entry point)

import "./styles/main.css";
import "./component/jumbotron.js";
import "./component/footer.js";
import main from "./view/main.js";

const boxConfirmed = document.querySelector("#globalConfirmed");
    const boxRecovered = document.querySelector("#globalRecovered");
    const boxDeath = document.querySelector("#globalDeath");
    const searchBarConfirmed = document.querySelector(".search-bar-confirmed");
    const searchBarRecovered = document.querySelector(".search-bar-recovered");
    const searchBarDeath = document.querySelector(".search-bar-death");
    const searchBarButtonConfirmed = document.querySelector("#searchBarButtonConfirmed");
    const searchBarButtonRecovered = document.querySelector("#searchBarButtonRecovered");
    const searchBarButtonDeath = document.querySelector("#searchBarButtonDeath");

let value;
console.log(value);


boxConfirmed.addEventListener("click", function(){
    getGlobalData(searchBarConfirmed, boxConfirmed, "confirmed");
    console.log("test");
});

boxRecovered.addEventListener("click", function(){
    getGlobalData(searchBarRecovered, boxRecovered, "recovered");
    console.log("test");
});

boxDeath.addEventListener("click", function(){
    getGlobalData(searchBarDeath, boxDeath, "death");
    console.log("test");
});

searchBarButtonConfirmed.addEventListener("click", () => {
    value = searchBarButtonConfirmed.value;
    const querySearch = document.getElementById("searchBarConfirmedField").value;
    console.log(value);
    getCountryData(querySearch, value, "confirmed");
});

searchBarButtonRecovered.addEventListener("click", () => {
    value = searchBarButtonRecovered.value;
    const querySearch = document.getElementById("searchBarRecoveredField").value;
    console.log(value);
    getCountryData(querySearch, value, "recovered");
});

searchBarButtonDeath.addEventListener("click", () => {
    value = searchBarButtonDeath.value;
    const querySearch = document.getElementById("searchBarDeathField").value;
    console.log(value);
    getCountryData(querySearch, value, "death");
});

./src/component/box-menu.js (act as a custom tag)

const template = document.createElement('template');
template.innerHTML = `
    <style>
        .container-menu{
            display: flex;
            flex-direction: column;
        
            width: 99%;
            padding: 10px;
            margin: auto;
        }
        
        .box-menu{
            display: flex;
            flex-direction: row;
            flex-grow: 1;
        
            padding: 10px;
        }
        
        .box{
            flex-grow: 1;
        
            margin: 1%;
            padding: 5px;
            border: 1px solid black;
            background-color: white;
            height: 100px;
            overflow-x: auto;
            flex-basis: auto;
            flex: 1 1;
            text-align: justify;
        
            box-shadow: 5px 10px;
            overflow-y: hidden;
        }
        
        .box:hover{
            box-shadow: 6px 12px rgb(44, 43, 43);
            border: 3px solid black;
            cursor: pointer;
        }
        
        .box:active{
            box-shadow: 6px 12px rgb(216, 216, 58);;
            border: 2px solid green;
        }
        
        .box-title{
            padding: 12px;
            
        }
        
        h3{
            text-align: center;
            font-size: 18px;
        }
        
        h5{
            text-align: center;
            font-size: 14px;
            margin-bottom: -1%;
        }
        
        .header-menu{
            font-family: 'Times New Roman', Times, serif;
            font-size: 24px;
            margin: 1% auto auto 0%;
        }
        
        .search-bar-confirmed, .search-bar-recovered, .search-bar-death{
            visibility: hidden;
            margin-left: 15%;
        }
    
    </style>

    <div>
        <h3 class="header-menu">
            See All About Covid-19 Info Updates in just 1 Website!
        </h3>
        <h5>Click the element to see complete updates info</h5>
    </div>
    <div class="container-menu">
        <div class="box-menu">
            <div id="globalConfirmed" class="box" value="confirmed"><h3 class="box-title">Confirmed Infected Cases</h3>
                <div id="total-infected"></div>

                <div class="search-bar-confirmed">
                    <input placeholder="Type country name" id="searchBarConfirmedField" type="search">
                    <button id="searchBarButtonConfirmed" type="submit" value="countryConfirmed">Search</button>
                </div>

                <div id="countryConfirmedField"></div>
            </div>
            <div id="globalRecovered" class="box"><h3 class="box-title">Fully Recovered from Infection</h3>
                <div id="total-recovered"></div>

                <div class="search-bar-recovered">
                    <input placeholder="Type country name" id="searchBarRecoveredField" type="search">
                    <button id="searchBarButtonRecovered" type="submit" value="countryRecovered">Search</button>
                </div>

                <div id="countryRecovered"></div>
            </div>
            <div id="globalDeath" class="box"><h3 class="box-title">Death Cases from Covid-19</h3>
                <div id="total-death"></div>

                <div class="search-bar-death">
                    <input placeholder="Type country name" id="searchBarDeathField" type="search">
                    <button id="searchBarButtonDeath" type="submit" value="countryDeath">Search</button>
                </div>

                <div id="countryDeath"></div>
            </div>
        </div>
    </div>
`;

class BoxMenu extends HTMLElement{
    constructor(){
        try{
            super();
            this.attachShadow({mode: 'open'});
            this.shadowRoot.appendChild(template.content.cloneNode(true));
            console.log("test");
        }catch{
            console.log("error here!");
        }
    }
}

window.customElements.define('box-menu', BoxMenu);

./src/view/main.js

import '../component/box-menu.js';

const main = () =>{
    function getGlobalData(searchBar,boxMenu,identifier){
            
        boxMenu.style.height = "320px";
        let writeData;
        let globalValue;
        let globalInfo;

        fetch(`https://covid19.mathdro.id/api`)
        .then(response => {
            return response.json();
        })
        .then(responseJson => {
            if(responseJson.error) {
                console.log(responseJson.error);
            } else {
                if(identifier == "confirmed"){
                    writeData = document.querySelector("#total-infected");
                    globalValue = formatNumber(responseJson.confirmed.value);
                    globalInfo = "people have been infected.";
                }else if(identifier == "recovered"){
                    writeData = document.querySelector("#total-recovered");
                    globalValue = formatNumber(responseJson.recovered.value);
                    globalInfo = "managed to be cured from covid19.";
                }else if(identifier == "death"){
                    writeData = document.querySelector("#total-death");
                    globalValue = formatNumber(responseJson.deaths.value);
                    globalInfo = "people lost their live because of this pandemic.";
                }
                writeData.innerHTML = `<p style="padding-left:15px; padding-right: 10px; text-align: center"> Globally, <strong>${globalValue}</strong> ${globalInfo}
                <br>Last Updated: ${responseJson.lastUpdate}</p>
                <h5 style="text-align: center; padding-left:10px; padding-right:10px; margin-bottom: 0%">Or you can type your country name for local data<br></h5>
                `;

                searchBar.style.visibility = "visible";
            }
        })
        .catch(error => {
            console.log(error);
        })
    }
    
    function formatNumber(num) {
        return num.toString().replace(/(\d)(?=(\d{3})+(?!\d))/g, '$1.')
    }

    function randomInteger(min, max) {
        return Math.floor(Math.random() * (max - min + 1)) + min;
    }

    function getCountryData(querySearch, value, identifier){
        const querySearchLowerCase = querySearch.toLowerCase();
        let data;
        let explanationString;
        let fieldSelector;
        let advice;

        fetch(`https://covid19.mathdro.id/api/countries/${querySearchLowerCase}`)
        .then(response =>{
            return response.json();
        })
        .then(responseJson =>{
            

            if(responseJson.error){
                 writeDataCountryConfirmed.innerHTML = `
                    <p style="padding-left:12px; padding-right: 12px;">
                        ${responseJson.error.message}
                        </p>
                 `;

            }else{
                if(value == "countryConfirmed"){
                    data = responseJson.confirmed.value;
                    explanationString = "people have been infected with covid-19";
                }else if(value == "countryRecovered"){
                    data = responseJson.recovered.value;
                    explanationString = "managed to be cured from covid19.";
                }else if(value == "countryDeath"){
                    data = responseJson.deaths.value;
                    explanationString = "people lost their live because of this pandemic.";
                }

                data = formatNumber(data);
                
                if(randomInteger(0,3) == 0){
                    advice = "<strong><br>Remember, use your mask everytime and everywhere.</strong>";
                }else if(randomInteger(0,3) == 1){
                    advice = "<strong><br>Never let your guard down, corona virus is still hunting us!</strong>"
                }else if(randomInteger(0,3) == 2){
                    advice = "<strong><br>Wash your hands, as long as you still use them.</strong>";
                }else{
                    advice = "<strong><br>Nothing better than staying at home in this situation.</strong>"
                }

                if(identifier == "confirmed"){
                    fieldSelector = document.querySelector("#countryConfirmedField");
                }else if(identifier == "recovered"){
                    fieldSelector = document.querySelector("#countryRecovered");
                }else if(identifier == "death"){
                    fieldSelector = document.querySelector("#countryDeath");
                }else{
                    console.log("Nothing Happened");
                }
                
                fieldSelector.innerHTML = `
                    <p style="padding-left:12px; padding-right: 12px; text-align:center">
                        In ${querySearch.toUpperCase()}, <strong>${data}</strong> ${explanationString}<br>
                        ${advice}
                        </p>
                        `;
            }
        })
    };
};
 

export default main;

after i bundle all file (not only all the previous files) and execute index.html file, i got this error message from Mozilla Console:

Uncaught TypeError: r is null https://ift.tt/3dnKKIP https://ift.tt/3dnKKIP https://ift.tt/3dnKKIP

And then i see the bundle.js file, i tried to locate where "r" are, but in column 7201, there is no "r". I cant wrote what's inside bundle.js here, please comment if you need to see that. i have done so many search a few days ago, including Youtube and StackOverflow, but nothing could help. So what is wrong with my code, and how i fix this? Any help will be appreciate. Thanks.




Aucun commentaire:

Enregistrer un commentaire