Handling empty json in ReactJS

Viewed 52

When retrieving the data from the backend via API, I want to check if a domain is valid or not. The issue is that when it is not valid (i.e. the domain does not exist in the backend, I receive an empty array [])

I have then used JSON.parse(JSON.stringify(obj)) in the frontend to get my data. I know that I could have used the response directly as it was, as I am sending it as JSON, but I wanted to test some things.

Please see the API below in the backend:

import Domains from "../models/DomainsModel.js";

export const Whois = async (req, res) => {
  try {
    const { domain } = req.body;

    const domainz = await Domains.findAll({
      where: {
        domain: domain,
      },
      attributes: {
        exclude: ["id", "userEmail", "arecord", "updatedAt"],
      },
      raw: true,
    }).then((result) => {
      console.log(result);
      if (result) {
        res.json(result);
      }
    });
  } catch (error) {
    console.log(error);
  }
};

Implementation of the function in front end :

const whoisForm = async (e) => {
  e.preventDefault();
  try {
    await axios
      .post("http://localhost:3001/whois", {
        domain: domain,
      })
      .then((resp) => {
        try {
          const datar = JSON.parse(JSON.stringify(resp));

          Moment.locale("en");

          let DomainWhois = datar.data[0].domain;
          let DomainCreatedAt = Moment(datar.data[0].createdAt).format(
            "DD MMM YYYY"
          );

          setDomainWhois(DomainWhois);
          setDomainCreatedAt(DomainCreatedAt);

          let eroareDomain =
            DomainWhois +
            " is already taken and was registered on: " +
            DomainCreatedAt;
          let successDomain =
            DomainWhois +
            " is available for purchase, you can register it now!";

          if (isEmptyObject(datar.data)) {
            setSuccessMesaj(successDomain);
          } else {
            setEroareMesaj(eroareDomain);
          }
        } catch (err) {
          console.log("err: " + err);
        }
      });
  } catch (error) {
    console.log("error" + error);
  }
};

I have tried the IF..ELSE with various functions, including:

  1. datar.data.length === 0
  2. !Array.isArray(datar.data) || !datar.data.length

I get the following error when response from API is empty []:

err: TypeError: Cannot read properties of undefined (reading 'domain')

What to do next?

UPDATE 1 The response for a successful response (i.e. data exists in the database) is:

[{"domain":"test.com","createdAt":"2022-09-20T13:33:08.000Z"}]

The response for an unsuccessful response (i.e. no data in the database) is:

[]

I want, when it is blank, to show a message that the domain you are trying to register is available.

Update 2

Response of JSON with data and without data enter image description here

1 Answers

It's unclear where you tried to check the conditions, but you're probably not preventing access to the undefined variable. I rewrote your code to take that into consideration

const whoisForm = async (e) => {
  e.preventDefault();
  try {
    await axios
      .post("http://localhost:3001/whois", {
        domain: domain,
      })
      .then((resp) => {
        try {
          Moment.locale("en");

          if (resp.data.length > 0) {
            let DomainWhois = resp.data[0].domain;
            let DomainCreatedAt = Moment(datar.data[0].createdAt).format(
              "DD MMM YYYY"
            );
            setDomainWhois(DomainWhois);
            setDomainCreatedAt(DomainCreatedAt);
            let eroareDomain =
              DomainWhois +
              " is already taken and was registered on: " +
              DomainCreatedAt;
            setEroareMesaj(eroareDomain);
          } else {
            let successDomain =
              DomainWhois +
              " is available for purchase, you can register it now!";
            setSuccessMesaj(successDomain);
          }
        } catch (err) {
          console.log("err: " + err);
        }
      });
  } catch (error) {
    console.log("error" + error);
  }
};

I don't think you need to parse and then stringify the resp since it's already an object.

Related