My FeedDiscussionsHashnode Enterprise
New
Sign in
Log inSign up
Learn more about Hashnode Headless CMSHashnode Headless CMS
Collaborate seamlessly with Hashnode Headless CMS for Enterprise.
Upgrade ✨Learn more

ReactJS: Taking care of null object in render

jim toby's photo
jim toby
·Oct 22, 2018

Hello,

I have an array that will be used to store objects in my state:

constructor() {
    super();
    this.state = {
      data: []
    }
 }

I will be retrieving these objects inside componentsDidMount(). In the render method, I try to access the contents of the array like this:

Object.keys(data[0])[0]

This simply gets me the first key of the first object inside the data array. In doing this, I get the error: Cannot convert undefined or null to object.

I do understand why I am getting this error. It's because at first, data array is empty. The way I took care of this was by adding an initial object inside the data array:

  constructor() {
    super();
    this.state = {
      data: [
        {
          "Please Wait": "Null"
        }
      ]
    };
  }

So in doing this, inside the componentDidMount() I will first need to clear the data array and than fetch the data to store inside the array. My question is, is this the correct way of handling this situation? Or is there a better and more effecient way?

Thanks!