I need that when a button is pressed, a state check is made, and depending on the result, one thing or another is done. Basically, check that there is no empty "value" field, and in that case redirect to another page of the application. With code it looks better:
const [formData, setFormData] = useState<ISignUpFormData>({
username: { value: "", valid: true, unique: true },
email: { value: "", valid: true, unique: true },
password: { value: "", valid: true },
birthdate: { value: "", valid: true },
});
const handleClick = async (e:any) => {
let canContinue = true;
const keys = Object.keys(formData);
keys.forEach(key => console.log()) // ??? keys is an array of strings, i need to access to "username".value to check if it is "" o not
}
The value fields are filled by controlled inputs
My question is: how do I loop through the keys of an object whose values are another object?
You can use Object.entries to get key and value and then check if any of the value has empty string.
Some naive implementation below.
Refer to this : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/entries
const object1 = {
username: { value: "", valid: true, unique: true },
email: { value: "", valid: true, unique: true },
password: { value: "", valid: true },
birthdate: { value: "", valid: true },
}
let hasEmptyString = false;
for (const [key, formKey] of Object.entries(object1)) {
if(formKey.value === ""){
hasEmptyString = true
break
}
}
if(!hasEmptyString){
// redirect to
}
console.log(hasEmptyString)
You can use Object.values() and find() ... it will return undefined if there is not entry with an empty string
const [formData, setFormData] = useState<ISignUpFormData>({
username: { value: "", valid: true, unique: true },
email: { value: "", valid: true, unique: true },
password: { value: "", valid: true },
birthdate: { value: "", valid: true },
})
const handleClick = () => {
const hasEmptyString = Object.values(formData).find(obj => obj.value === '');
//Returns object with empty string id there is any
//returns undefined if there is not entry with empty string
console.log(hasEmptyString);
}