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:
- datar.data.length === 0
- !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.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.