"Can't read property of undefined" - Never Again!!🚀

Here is how you can prevent the most irritating error in ReactJS when fetching data with elegance ✨

can't read value of undefined - If you have made your hand dirty in coding with JS, you are sure to have encountered this irritating error that would have broken your app for god knows how many times. No more of it! because today what I'll tell you will make sure you are never going to be bugged by this error😊

The concept that we will be using to get rid of this problem is called Optional Chaining🔗, but first, let us see the most common cases when this error occurs and how it is solved in the traditional way.

This error is mostly found when we are fetching data from an API to be rendered in our app which typically looks like this

export default function App() {
  const [apiData, setApiData] = useState(null);

  useEffect(() => {
    axios
      .get("https://hub.dummyapis.com/singlelist?text=Test&noofRecords=5")
      .then((res) =>  {setApiData(res.data)})
  }, []);

  return (
    <div className="App">
// One can also do if(apiData) { map the data } or
      { apiData && apiData.map((elem)=> 
        return <h1>elem.value</h1>
      )}
    </div>
  );
}

JavaScript being asynchronous proceeds to execute the part of the code meant to render the data before the data is fetched, hence we imply the use of && operator or if(data) to make sure the part of rendering the code runs only when the data is fetched completely.

Now the optional chaining operator ?. is just like the chain operator . but with a twist! The regular chain operator gives an error if the reference value is null or undefined (collectively called as nullish), it will simply return undefined✨. Hence the above code can be written as

 return (
    <div className="App">
      { apiData?.map((elem)=> return <h1>elem.value</h1>)} // Elegance✨
    </div>
  );

Optional chaining will also work in cases where we have optional props let's say for example

var a = {
name : "Rias Gremory",
}

var b = {
name : "Issey Hyodo",
boost: ()=> {console.log("BOOST!")}
}

const dxd = [a,b] //An array of both the objects

//Now let's say we want to map the array and run the function if present
//We can easily do this by
dxd.map((elem)=>elem?.boost?.())

//PS: If you know, you know🏯

Well, this is all about optional chaining. Hope I was able to add some value to your coding arsenal😊

PS: I'm also an intermediate in ReactJs, I'm learning new concepts every day and applying them in my code to better myself. I'll be sure to put up a blog if something I learned is going to be of value to the community✨

Be Awesome, Be You!