DEV Community

Cover image for Enumerating JavaScript Object properties and its usage in React
Vincent Kipyegon
Vincent Kipyegon

Posted on

Enumerating JavaScript Object properties and its usage in React

An object in javascript is a collection of key-values pairs,also called a property. Anything that is not a number,string,undefined,symbol or Boolean is an object. Null is a special kind of object, by the way. There are 3 types of objects in Javascript: object Literal {},arrays [] and functions.

Object literals, though, contain certain payload properties that might come from a REST api or user input,before rendering them it is important to check for their presence. In react, we always assume and check if each and every object has an id property.
Here are 3 ways to do that.

  1. Using the in method

The in JavaScript method checks if the property exists in an object,returns true if present,false if absent.

let user={name:"Mark Twain",id:1};

 if("id" in user)
console.log(` ${user.id}  found `)
else
console.log(`The property does not exist`)

Enter fullscreen mode Exit fullscreen mode
  1. Checking if an object property is undefined

If a property of an Object does not exist, it will always be undefined,so to check we use this comparison expression: javascript user.id !== undefined It will be true if the object property exists,false if not, in this we assume the object is not available.

In web development, moreso React.js, we always presume that every object from REST api has an id property.

let user={name:"Mark Twain",id:1}
// in our case weโ€™re checking if user has property id
if (user.id !== undefined) console.log(` ${user.id} found `);
else console.log(`The property does not exist`);
Enter fullscreen mode Exit fullscreen mode

3.Using has hasOwnProperty method
The hasOwnProperty is a built in method that takes the object and evaluates it against a given property,return true if property exists or false if not.

let user={name:"Mark Twain",id:1}
if (user.hasOwnProperty("id")) console.log(` ${user.id} found`);
else console.log(`user does not exist`);
Enter fullscreen mode Exit fullscreen mode

We can write a javascript fuction test all of this;

let user={} // initially user object its null

async function fetchUser () {
  // we're fetching user with id number 1;
  const url = "https://jsonplaceholder.typicode.com/users/1";
    try {

      const response = await fetch(url);
      const payload = await response.json();


      // check if object exists by checking if  id property is not  undefined..
      // also note the optional chaining, if nothing returned, if payload is null or undefined, 
//it will just end there;
      if (payload?.id !== undefined) return payload
    } catch (error) {
      console.error(error?.message);
    }
}



Enter fullscreen mode Exit fullscreen mode

We then fetch the user from the server when DOM is loaded.

// fetch user when the DOM loads
 window.addEventListener("DOMContentLoaded", async ()=>{
// we the assign user to response object
user= await fetchUser() // asynchronous network request to get a user object
})
Enter fullscreen mode Exit fullscreen mode

Finally, we can create a React component that uses the 3 methods in setting state,at useEffect and JSX expressions and evaluations.

function RenderPost() {
  const [post, setPost] = React.useState({}); // we start with an empty object literal
  const [spinner, setSpinner] = React.useState(false);

  // we're fetching one post
  const fetchPost = async (postId = 1) => {
    try {
      setSpinner(true);
      const url = `https://jsonplaceholder.typicode.com/posts/${postId}`;
      const response = await fetch(url);
      const payload = await response.json();

      // check if object exists by checking if  id property is not  undefined..
      if (payload?.id !== undefined) setPost(payload);
      setSpinner(false);
    } catch (error) {
      setSpinner(false);
      console.error(error?.message);
    }
  };
  React.useEffect(() => {
    // if the post  is empty just fetch it, we use negation symbol to do that

    if (!post.hasOwnProperty("id")) fetchPost(1);
  }, []);
  // pending state
  if (spinner)
    return (
      <div className="container">
        <p>Loading post</p>
      </div>
    );

  // resolved or rejected

  return (
    <div className="container">
      {/**We use the in Method to check if object has id property */}
      {"id" in post ? (
        <div>
          <h3>{post.title}</h3>
          <p>{post.body}</p>
        </div>
      ) : (
        <p>No post found</p>
      )}
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

We check for undefined inside fetchPost function to check if payload object was found, hasOwnProperty inside the useEffect to see if post object is already available and in method in JSX to evaluate presence of the object before rendering it.

Top comments (0)