0

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

7
  • It would be better if you can add your API response also for reference. Commented Sep 22, 2022 at 10:51
  • Hello @SatejBidvai , I have provided the API response to the main question. Thanks :) Commented Sep 22, 2022 at 13:17
  • [][0].domain doesn't exist in [] so if ([].length > 1) { ... } run your logic maybe try or even if (datar[0].hasOwnProperty('domain') === true) { ... } Commented Sep 22, 2022 at 13:21
  • Hello @CotyEmbry , I have tried both and they are not working, the reason would be that when doing a console.log ( datar.data[0].hasOwnProperty('domain') ), returns true if it has data, if not it will not return anything, I would expect false, but ... Commented Sep 22, 2022 at 13:57
  • Assuming the array you provided is the response.data: When response from API is empty, your data[0] does not exists, so data[0].domain is giving you an error as data[0] itself does not exists. Commented Sep 22, 2022 at 14:31

1 Answer 1

1
+100

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you @diedu , it works, I am reading the implementation to see exactly the lack of code from my side

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.