Is there a way to access various history.pushState events when using window.popState in JavaScript?

In my code, there are two pushStates that I need to read separately and execute different functions for. However, when the form is not submitted, the related pushState does not trigger and results in this error:

Uncaught TypeError: Cannot read property 'name' of null at window.onpopstate (poke.js:18)
. This code is included inside the event 'DOMContentLoaded'. How can I handle reading different pushStates on onpopstate?

//code

window.onpopstate = function(event){
        if(event.state.name){
            
            getInfo(event.state.get_info,cards,pgHeader,pokeInfo,pokeDiv);
        }else {
            
            showAll(cards,pgHeader,pgParagraph,pokeInfo,pokeDiv);
        };
    };

    all_poke.onclick = ()=>{
        history.pushState(null,null,"/all_pokemons")
        pokeInfo.innerHTML = '';
        showAll(cards,pgHeader,pgParagraph,pokeInfo,pokeDiv);
        return false;
    }
  
    form.onsubmit = function (){
        
        pgParagraph.innerHTML = '';
        var name = searchBox.value;
        history.pushState({name},null,`${name}/info`)
        getInfo(name,cards,pgHeader,pokeInfo,pokeDiv)
        return false;
    }

Answer №1

To avoid errors when accessing properties in JavaScript objects, you can use optional chaining with the ?. operator. This way, if a property doesn't exist, it will return undefined instead of throwing an error.

if (event.state?.name) {

If you need to support older browsers or prefer a different approach, you can simply check if the state property is null. This covers one of the possible scenarios in your code.

if (event.state !== null) {

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

Is there a way I can finish animating these divs in a diagonal motion?

I successfully made the blue and red divs move diagonally and switch positions. Now I am looking to achieve the same effect with the green and pink divs using a similar function. I am unsure about setting the position of both divs to 0 and 350 for those p ...

Utilizing analytics.js independently of the react-ga library

Is there a way to integrate Google Analytics into my React app without using the react-ga package? I specifically want to access the ga function in a separate JavaScript file as well as within a React component. How can I achieve this by importing the anal ...

Synchronously executing Twitter posts

Hello there! I've been using this code found here to embed Twitter posts on my website. It's been working perfectly on certain pages, like in the forums, but I've run into an issue while browsing through user profiles. The post history for e ...

Angular JS has a unique feature of a scrollable drop-up menu that allows

https://i.sstatic.net/MOUqO.pngHere is the code snippet for my Dropup component: <div class="dropup"> <button class="btn btn-primary btn-raised dropdown-toggle" type="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false> ...

Swap out AJAX following a successful retrieval and when managing errors

I currently have a basic AJAX load function set up to load a specific URL: <div id="load"> <h1 id="status">Loading...</h1> </div> <script type="text/javascript"> $(document).ready(function(){ $.ajaxSetup({cache: false}); var ...

Exploring Symfony2 controller integration with Javascript arguments

I am currently working on a project with Symfony2 and I have a question regarding receiving arguments from a template in a controller. My goal is to take the value of the argument and store it in the database. The argument's value will be generated by ...

Navigating the authorization header of an API request in a Node environment

const authHeader = req.headers["authorization"]; I have a question that may come across as basic - why do we use ["authorization"] instead of just .authorization? After some research, I discovered it had to do with case sensitivity but ...

Expanding the width of Material UI Javascript Dialog Box

Currently, I am utilizing the dialog feature from Material UI in my React JS project and I am looking to expand its width. After some research, I discovered that there is a property called maxWidth which allows you to adjust the width of the dialog. Howe ...

Having Trouble with Your React.js Rendering?

I'm starting to learn React.js but I'm having trouble rendering it into the HTML. I can't figure out what's wrong. Any help would be greatly appreciated. Below are the HTML and JSX code: (Note: Full links to the react library are incl ...

A guide on breaking down the ID passed from the backend into three segments using React JS

I pulled the data from the backend in this manner. https://i.stack.imgur.com/vMzRL.png However, I now require splitting this ID into three separate parts as shown here. https://i.stack.imgur.com/iy7ED.png Is there a way to achieve this using react? Bel ...

Using CSS in combination with AngularJS, you can create a dynamic growth effect for a div element that initially

I am currently using AngularJS to dynamically add divs to a section. My goal is to have each div start with a static width and then grow dynamically as I continue to add more divs. How can I achieve this? The following code is not producing the desired re ...

Is the iCheck feature designed to block all parent click events?

I've developed an "interaction tracker" system that collects anonymous data on clicked page elements. By implementing an event listener for clicks on the body, I can track interactions with any element on my site successfully. However, interestingly ...

Issue when sending PHP Papa Parse object through AJAX

I am currently working on extracting a CSV local file in PHP using AJAX and have found success with Papa Parse. However, I am facing difficulties passing the results with AJAX. Despite trying various methods such as JSON.stringify, passing only the first f ...

Extracting the href attribute from a child <a> tag

I am struggling to retrieve the value of the href within the code structure below: <div class=""> <div class=""> <div class=""> <a href=""><img src=""></a> </div> </div> </div> The m ...

What is the best way to activate an alert or swal function just once instead of repeatedly?

I am just starting to learn Angular. Currently, I have an application that contains two variables related to the status of financial transactions. These variables are: tab1TrxMessage, which holds any important messages, and tab1TrxStatus that indicates wh ...

Exploring a JavaScript object to verify if a property contains nested data elements

I am currently working on traversing through the object above in order to determine if a contact is a member of a specific list. For instance, if the user is a member of the list with an ID of 2022, I want to display their first name (which is also includ ...

Attempting to reset the altered values proves ineffective in different Ctrl instances within AngularJS

I'm feeling a bit disoriented regarding my current issue. The scenario involves two views and a controller that interact with a service. The first view consists of a table list containing items loaded from a WebAPI. The service sends requests to the s ...

Using Selenium WebDriver to Extract Variables from JavaScript SourceCode

Currently, I am dealing with a web page source code that utilizes JavaScript to display text. Below is an excerpt from the source: var display_session = get_cookie("LastMRH_Session"); if(null != display_session) { document.getElementById("sessionDIV") ...

Rails confirmation feature malfunctioning

I have been struggling to figure out where I am going wrong with this code even though I've checked several posts. I am using Ruby on Rails and trying to run the following snippet: <%= link_to 'Destroy', article_path(article), ...

Unusual marking on the navigation bar

Currently, I am making updates to a website that was created by a previous employee long before I joined the team. One of the requested changes is to eliminate the orange box surrounding the navigation links. The navigation appears to be generated using Ja ...