Skip to content Skip to sidebar Skip to footer

Typeerror: Cannot Read Property 'service' of Undefined React

Author avatar

Use ES6 Arrow Functions to Resolve "TypeError: Cannot read property '<your property name>' of undefined"

Zachary Bennett

Forepart Finish Spider web Development

Introduction

If you are a React programmer or are merely learning to plan in JavaScript, you might take run into this dreaded error while trying to read a property off of the this keyword:

                                      1                    TypeError: Cannot read property '<your property name>' of undefined                                  

If you see this error while writing React, the odds are loftier that you are trying to utilize a function within another role and are trying to access the this keyword within the nested function. But why does this happen?

This guide will swoop into how role scope works in JavaScript. Yous will learn why this mistake occurs and what you can do to fix information technology.

The Problem and an Initial Solution

Let's say that you accept but written a small React Component that looks similar this:

                                      1                    class                                                            FishSpecies                                                            Extends                                                            React                    .                    Component                                                            {                                                            2                                                            constructor                    (                    props                    )                                                            {                                                            3                                                            super                    (                    props                    )                    ;                                                            4                                                            this                    .                    land                                                            =                                                            {                                                            five                                          clickCount                    :                                                            0                                                            half dozen                                                            }                    ;                                                            7                                                            }                                                            8                    9                                                            onFishClicked                    (                    )                                                            {                                                            10                                                            this                    .                    setState                    (                    function                    (                    prevState                    ,                                          props                    )                                                            {                                                            eleven                                                            return                                                            {                                          clickCount                    :                                          prevState                    .                    clickCount                                                            +                                                            1                                                            }                    ;                                                            12                                                            }                    )                    ;                                                            thirteen                                                            }                                                            14                    xv                                                            return                    (                    )                                                            {                                                            xvi                                                            return                                                            (                                                            17                                                            <                    ul                    >                                                            18                                                            {                    {                                                            this                    .                    props                    .                    fish                    .                    map                    (                    function                    (                    fish                    )                                                            {                                                            19                                                            return                                                            <                    Fish                                                            proper noun                    =                    {                    fish                    .                    name                    }                                                            onClick                    =                    {                    this                    .                    onFishClicked                    }                                                            />                                                            twenty                                                            }                    )                    }                    }                                                            21                                                            </                    ul                    >                                                            22                                                            )                                                            23                                                            }                                                            24                                        }                                  

jsx

At get-go, this component looks pretty straightforward. All this component does is receive a list of fish objects via props and render a Fish component for each 1, passing downwardly a couple of props to each fish. Nonetheless, if you create this component and add to a existent React app, information technology will fail. You will see an mistake that looks similar:

                                      i                    TypeError: Cannot read property 'onFishClicked' of undefined                                  

Oh no, there it is—the dreaded TypeError! So, why is this happening? This error informs you that this is undefined. Specifically, onClick={this.onFishClicked} fails for this reason. The reason the code is unable to access this here is because of how scope works in JavaScript.

Nether the hood, functions are objects in JavaScript. When you create a part in JavaScript, it gets its own telescopic depending upon the context in which it is instantiated. In this case, there actually is no context, and so this is actually undefined ! Substantially, the lawmaking is running in strict style within the React framework and and then the global context is not used in favor of no context at all. Cheque out these docs for more info.

So how tin can you fix this? Well, you have a number of options. In the following section volition demonstrate the best and most modern means of fixing this fault.

The ES6 Solution

And so you've diagnosed the problem. You need to make sure that your functions have access to the this context of your class component! To do this, you lot can use ES6 arrow functions.

Apart from making your lawmaking more succinct and readable, arrow functions serve another purpose. It is not immediately obvious, but arrow functions play a big part in how context is passed down to functions. Essentially, when you declare a function using the arrow syntax you lot are telling the JavaScript code to bind the current context of this into the new function that is existence created. This is not immediately obvious considering this binding is done implicitly as compared to the explicit means of binding this by using the .bind method.

Permit's meet how you can use pointer functions to fix your code!

                                      1                    class                                                            FishSpecies                                                            Extends                                                            React                    .                    Component                                                            {                                                            two                                                            constructor                    (                    props                    )                                                            {                                                            3                                                            super                    (                    props                    )                    ;                                                            4                                                            this                    .                    state                                                            =                                                            {                                                            five                                          clickCount                    :                                                            0                                                            6                                                            }                                                            seven                                                            }                                                            8                    9                                                            onFishClicked                    (                    )                                                            {                                                            ten                                                            this                    .                    setState                    (                    (                    prevState                    ,                                          props                    )                                                            =>                                                            {                                                            11                                                            return                                                            {                                          clickCount                    :                                          prevState                    .                    clickCount                                                            +                                                            1                                                            }                    ;                                                            12                                                            }                    )                    ;                                                            13                                                            }                                                            14                    fifteen                                                            render                    (                    )                                                            {                                                            sixteen                                                            return                                                            (                                                            17                                                            <                    ul                    >                                                            18                                                            {                    {                                                            this                    .                    props                    .                    fish                    .                    map                    (                    fish                                                            =>                                                            {                                                            19                                                            render                                                            <                    Fish                                                            name                    =                    {                    fish                    .                    name                    }                                                            onClick                    =                    {                    this                    .                    onFishClicked                    }                                                            />                                                            xx                                                            }                    )                    }                    }                                                            21                                                            </                    ul                    >                                                            22                                                            )                                                            23                                                            }                                                            24                                        }                                  

jsx

Voila! It was a simple change to both of the role declarations above, but now your dreaded TypeError is gone because the function you are passing into Array.map within the render function has access to your component'due south this context. And this was all accomplished simply past changing how you alleged your part.

Conclusion

Pointer functions are a powerful means of binding the electric current context of this into nested functions. Unfortunately, this major benefit is implicit and then y'all would never know about it just by looking at its usage. Well-nigh, if non all, of your function declarations within your React components should exist declared as arrow functions. Doing this will aid you to avert confusion when it comes to the context of this and what it gets bound to.

taoworkly.blogspot.com

Source: https://www.pluralsight.com/guides/use-es6-arrow-functions-to-resolve-%22typeerror:-cannot-read-property-'lessyour-property-namegreater'-of-undefined%22

Post a Comment for "Typeerror: Cannot Read Property 'service' of Undefined React"