I am struggling with managing the state of a react form - reactjs

i have this json object which i use to map the form. I have a lot of nested questions. It is used for medical purposes. Here's an portion of the json
parts: [
{
title: "Surgery-related",
questions: [
{
type: "radio",
required: true,
label: "Timing of surgery",
name: "timing_of_surgery",
options: [
{
label: "Emergent non-cardiac surgery",
value: "emergent_non_cardiac_surgery",
},
{
label: "Urgent non-cardiac surgery",
value: "urgent_non_cardiac_surgery",
},
{
label: "Time-sensitive non-cardiac surgery",
value: "time_sensitive_non_cardiac_surgery",
},
{
label: "Elective non-cardiac surgery",
value: "elective_non_cardiac_surgery",
name: "elective_non_cardiac_surgery",
nestedQuestion: {
type: "radio",
options: [
{
label: "Possible to defer non-cardiac surgery",
value: "possible_to_defer_non_cardiac_surgery",
},
{
label: "Not possible to defer non-cardiac surgery",
value: "not_possible_to_defer_non_cardiac_surgery",
},
],
},
},
],
},
{
type: "select",
required: true,
label: "Type of surgery or intervention",
name: "type_of_surgery_or_intervention",
options: [
{
value: "Low surgical risk (<1%)",
titles: [
"Breast",
"Dental",
"Endocrine: thyroid",
"Eye",
"Gynaecological: minor",
"Orthopaedic minor (meniscectomy)",
"Reconstructive",
"Superficial surgery",
"Urological minor: (transurethral resection of the prostate)",
"Video assisted thoracic surgery minor lung resection",
],
},
{
value: "Intermediate surgical risk (1-5%)",
titles: [
"Carotid asymptomatic (coronary endarterectomy or coronary artery stenting)",
"Carotid symptomatic (coronary endarterectomy)",
"Endovascular aortic aneurysm repair",
"Head or neck surgery",
"Intraperitoneal: splenectomy, hiatal hernia repair, cholecystectomy",
"Intrathoracic: non-major",
"Neurological or orthopaedic: major (hip and spine surgery)",
"Peripheral arterial angioplasty",
"Renal transplants",
"Urological or gynaecological: major",
],
},
{
value: "High surgical risk (>5%)",
titles: [
"Adrenal resection",
"Aortic and major vascular surgery",
"Carotid symptomatic (Carotid artery stenting)",
"Duodenal-pancreatic surgery",
"Liver resection, bile duct surgery ",
"Oesophagectomy",
"Open lower limb revascularization for acute limb ischaemia or amputation",
"Pneumonectomy (video-assisted thoracic surgery or open surgery)",
"Pulmonary or liver transplant",
"Repair of perforated bowel",
"Total cystectomy",
],
},
],
},
{
type: "select",
required: true,
label: "Bleeding risk",
name: "bleeding_risk",
options: [
{
value: "Minor bleeding risk",
titles: [
"Cataract or glaucoma procedure",
"Dental procedures: extractions (1–3 teeth), periodontal surgery, implant positioning endodontic (root canal) procedures, subgingival scaling/cleaning",
"Endoscopy without biopsy or resection",
" Superficial surgery (e.g. abscess incision, small skin excisions/ biopsy)",
],
},
{
value: "Low bleeding risk",
titles: [
"Abdominal surgery: cholecystectomy, hernia repair, colon resection",
"Breast surgery",
"Complex dental procedures (multiple tooth extractions)",
"Endoscopy with simple biopsy",
"Gastroscopy or colonoscopy with simple biopsy",
"Large-bore needles procedures (e.g. bone marrow or lymph node biopsy)",
"Non-cataract ophthalmic surgery",
"Small orthopaedic surgery (foot, hand arthroscopy)",
],
},
{
value: "High bleeding risk",
titles: [
"Abdominal surgery with liver biopsy, extracorporeal shockwave lithotripsy",
"Extensive cancer surgery (e.g. pancreas, liver)",
"Neuraxial (spinal or epidural) anaesthesia",
"Neurosurgery (intracranial, spinal) ",
"Major orthopaedic surgery ",
"Procedures with vascular organ biopsy (kidney or prostate)",
"Reconstructive plastic surgery",
"Specific interventions (colon polypectomy, lumbar puncture, endovascular aneurysm repair)",
"Thoracic surgery, lung resection surgery",
" Urological surgery (prostatectomy, bladder tumour resection)",
"Vascular surgery (e.g. abdominal aortic aneuvrysm repair, vascular bypass)",
],
},
],
},
],
},
{
title: "Patient-related",
questions: [
{
type: "input",
input_type: "text",
placeholder: "Enter patient's name",
required: true,
label: "Patient's name",
name: "patient_name",
},
{
type: "checkbox",
required: false,
label: "Cardiovascular risk factor",
name: "cardiovascular_risk_factor",
options: [
{
label: "Hypertension",
value: "hypertension",
},
{
label: "Diabetes",
value: "diabetes",
},
{
label: "Dyslipidemia",
value: "dyslipidemia",
},
{
label: "Smoking",
value: "smoking",
},
{
label: "Age greater than or equal to 65 years",
value: "age_greater_than_65_years",
},
{
label: "Family history of cardiovascular disease",
value: "family_history_of_cardiovascular_disease",
required: true,
nestedQuestion: {
type: "checkbox",
options: [
{
label:
"Myocardial infarction or sudden death <55 years with father or brother",
value:
"myocardial_infarction_or_sudden_death_less_than_55_years_with_father_or_brother",
},
{
label:
"Myocardial infarction or sudden death <65 years with mother or sister",
value:
"myocardial_infarction_or_sudden_death_less_than_65_years_with_mother_or_sister",
},
{
label:
"Cerebrovascular accident <45 years with parents or brother/sister",
value:
"cerebrovascular_accident_less_than_45_years_with_parents_or_brother_sister",
},
],
},
},
],
},
{
type: "checkbox",
label: "Antecedents",
name: "antecedents",
sections: [
{
title: "Cardiovascular disease ",
options: [
{
label: "Heart failure",
value: "heart_failure",
namee: "heart_failure",
nestedQuestion: {
type: "radio",
options: [
{
label: "Stable heart failure",
value: "stable_heart_failure",
},
{
label: "Unstable heart failure",
value: "unstable_heart_failure",
},
],
},
},
{
label: "Coronary artery disease",
value: "coronary_artery_disease",
},
{
label: "Vasopastic angina",
value: "vasopastic_angina",
},
{
label: "Mechanical prosthetic valve",
value: "mechanical_prosthetic_valve",
name: "mechanical_prosthetic_valve",
nestedQuestion: {
type: "checkbox",
options: [
{
label:
"Mechanical aortic valve replacement(AVR), associated with ",
value:
"mechanical_aortic_valve_replacement_associated_with",
name: "mechanical_aortic_valve_replacement_associated_with",
nestedQuestion: {
type: "checkbox",
options: [
{
label: "Atrial fibrillation",
value: "atrial_fibrillation1",
},
{
label: "Previous thromboembolism, ",
value: "previous_thromboembolism",
},
{
label: "Severe left ventricular dysfunction ",
value: "severe_left_ventricular_dysfunction",
},
{
label: "Hypercoagulable state",
value: "hypercoagulable_state",
},
]
}
},
{
label:
"Older-generation mechanical aortic valve replacement ",
value:
"older_generation_mechanical_aortic_valve_replacement",
},
{
label: "Mechanical mitral valve replacement",
value: "mechanical_mitral_valve_replacement",
},
],
},
},
{
label: "Atrial fibrillation",
value: "atrial_fibrillation",
},
{
label: "Other rythmic antecedents",
value: "other_rythmic_antecedents",
},
{
label: "Venous thromboembolism",
value: "venous_thromboembolism",
},
],
},
{
title: "Non cardiovascular disease",
options: [
{
label: "Diabetes mellitus",
value: "diabetes_mellitus",
},
{
label: "Renal failure",
value: "renal_failure",
},
],
},
],
},
],
},
{
title: "Examination",
questions: [
{
type: "checkbox",
required: true,
label: "Examination",
name: "examination",
options: [
{
label: "Asymptomatic",
value: "asymptomatic",
default: true,
},
{
label: "Newly detected murmurs",
value: "newly_detected_murmurs",
},
{
label: "Chest pain",
value: "chest_pain",
},
{
label: "Symptoms/signs suggestive of cardio-vascular disease",
value: "symptoms_signs_suggestive_of_cardiovascular_disease",
},
{
label:
"Poor functional capacity (METs<4 –if the patient cannot climb two flights of stairs-)",
value: "poor_functional_capacity",
},
{
label: "High clinical risk factor : (RCRI >= 1)",
value: "high_clinical_risk_factor",
name: "high_clinical_risk_factor",
required: true,
nestedQuestion: {
type: "checkbox",
options: [
{
label: "Ischaemic heart disease",
value: "ischaemic_heart_disease",
},
{
label: "Cerebrovascular disease",
value: "cerebrovascular_disease",
},
{
label: "History of congestive heart failure",
value: "history_of_congestive_heart_failure",
},
{
label: "Insulin therapy for diabetes",
value: "insulin_therapy_for_diabetes",
},
{
label: "Serum creatinine level ≥2 mg/dL",
value:
"serum_creatinine_level_greater_than_or_equal_to_2_mg_per_dL",
},
{
label: "High-risk surgery",
value: "high_risk_surgery",
},
],
},
},
{
label: "Abnormal ECG",
value: "abnormal_ecg",
name: "abnormal_ecg",
required: true,
nestedQuestion: {
type: "checkbox",
options: [
{
label: "Pathological Q wave",
value: "pathological_q_wave",
},
{
label: "ST-T wave changes",
value: "st_t_wave_changes",
},
{
label: "Non-sinus rhythm",
value: "non_sinus_rhythm",
},
{
label: "Left bundle branch block",
value: "left_bundle_branch_block",
},
],
},
},
{
label: "High NT-pro-BNP/BNP",
value: "high_nt_pro_bnp_bnp",
},
{
label: "Acute coronary syndrome",
value: "acute_coronary_syndrome",
},
],
},
],
},
],
The way i render this form is using recursion. I have this jsx component named Question.jsx which i pass with it the question. Where i'm stuck is to manage the state of the hole form in one useState hook object. And espacialy when it comes to nested questions with levels of more the 2. As i need to update the parent. I realy need help please !

Related

My multi select is not working, and I can't save data into database

I tried to make a function that add list of country. But it's not working at the last input (Những ngôn ngữ dịch. I can't save it into database to. What should I do?
I tried to add as much as possible country on the last input. But it didn't show. Here are my code:
import '../../css/style.css';
import { useEffect } from "react";
import { useState, useSelector } from "react";
import { ajaxCallGetUrlDemo, ajaxCallPost } from "../libs/base";
import Select from 'react-select'
import { Const_Libs } from "../libs/Const_Libs";
const ModalAddNgonNgu = (props) => {
const { handleGetLanguage } = props;
const [ngonNgu, setNgonNgu] = useState({
language_name: '',
main_lang: '',
title_lang: '',
describe_lang: '',
author_lang: '',
rate_lang: '',
reviews_lang: '',
// translate_list: []
translate_list: []
});
function SelectMainLanguage() {
const [selectedOption, setSelectedOption] = useState({});
const options = [
{ value: 'Vietnamese', label: 'Vietnamese' },
{ value: 'English', label: 'English' },
{ value: 'Chinese', label: 'Chinese' },
{ value: 'Japanese', label: 'Japanese' },
{ value: 'German', label: 'German' },
];
const handleChangeOption = () => {
return setSelectedOption;
}
useEffect(() => {
if (selectedOption.value) {
console.log(selectedOption)
setNgonNgu({ ...ngonNgu, main_lang: selectedOption.value })
}
}, [selectedOption])
// {console.log(selectedOption)}
return (
<Select className={`col-12 o-languages`}
value={ngonNgu.main_lang ? { value: ngonNgu.main_lang, label: ngonNgu.main_lang } : { value: "Chọn ngôn ngữ chính", label: "Chọn ngôn ngữ chính" }}
onChange={handleChangeOption()}
options={options} />
)
}
function SelectTransLanguage() {
const [selectedOption, setSelectedOption] = useState({});
const options = [
{ value: "AF", label: "Afghanistan" },
{ value: "AL", label: "Albania" },
{ value: "DZ", label: "Algeria" },
{ value: "AS", label: "American Samoa" },
{ value: "AD", label: "Andorra" },
{ value: "AO", label: "Angola" },
{ value: "AI", label: "Anguilla" },
{ value: "AQ", label: "Antarctica" },
{ value: "AG", label: "Antigua And Barbuda" },
{ value: "AR", label: "Argentina" },
{ value: "AM", label: "Armenia" },
{ value: "AW", label: "Aruba" },
{ value: "AU", label: "Australia" },
{ value: "AT", label: "Austria" },
{ value: "AZ", label: "Azerbaijan" },
{ value: "BS", label: "Bahamas The" },
{ value: "BH", label: "Bahrain" },
{ value: "BD", label: "Bangladesh" },
{ value: "BB", label: "Barbados" },
{ value: "BY", label: "Belarus" },
{ value: "BE", label: "Belgium" },
{ value: "BZ", label: "Belize" },
{ value: "BJ", label: "Benin" },
{ value: "BM", label: "Bermuda" },
{ value: "BT", label: "Bhutan" },
{ value: "BO", label: "Bolivia" },
{ value: "BA", label: "Bosnia and Herzegovina" },
{ value: "BW", label: "Botswana" },
{ value: "BV", label: "Bouvet Island" },
{ value: "BR", label: "Brazil" },
{ value: "IO", label: "British Indian Ocean Territory" },
{ value: "BN", label: "Brunei" },
{ value: "BG", label: "Bulgaria" },
{ value: "BF", label: "Burkina Faso" },
{ value: "BI", label: "Burundi" },
{ value: "KH", label: "Cambodia" },
{ value: "CM", label: "Cameroon" },
{ value: "CA", label: "Canada" },
{ value: "CV", label: "Cape Verde" },
{ value: "KY", label: "Cayman Islands" },
{ value: "CF", label: "Central African Republic" },
{ value: "TD", label: "Chad" },
{ value: "CL", label: "Chile" },
{ value: "CN", label: "China" },
{ value: "CX", label: "Christmas Island" },
{ value: "CC", label: "Cocos (Keeling) Islands" },
{ value: "CO", label: "Colombia" },
{ value: "KM", label: "Comoros" },
{ value: "CG", label: "Congo" },
{ value: "CD", label: "Congo The Democratic Republic Of The" },
{ value: "CK", label: "Cook Islands" },
{ value: "CR", label: "Costa Rica" },
{ value: "CI", label: "Cote D'Ivoire (Ivory Coast)" },
{ value: "HR", label: "Croatia (Hrvatska)" },
{ value: "CU", label: "Cuba" },
{ value: "CY", label: "Cyprus" },
{ value: "CZ", label: "Czech Republic" },
{ value: "DK", label: "Denmark" },
{ value: "DJ", label: "Djibouti" },
{ value: "DM", label: "Dominica" },
{ value: "DO", label: "Dominican Republic" },
{ value: "TP", label: "East Timor" },
{ value: "EC", label: "Ecuador" },
{ value: "EG", label: "Egypt" },
{ value: "SV", label: "El Salvador" },
{ value: "GQ", label: "Equatorial Guinea" },
{ value: "ER", label: "Eritrea" },
{ value: "EE", label: "Estonia" },
{ value: "ET", label: "Ethiopia" },
{ value: "XA", label: "External Territories of Australia" },
{ value: "FK", label: "Falkland Islands" },
{ value: "FO", label: "Faroe Islands" },
{ value: "FJ", label: "Fiji Islands" },
{ value: "FI", label: "Finland" },
{ value: "FR", label: "France" },
{ value: "GF", label: "French Guiana" },
{ value: "PF", label: "French Polynesia" },
{ value: "TF", label: "French Southern Territories" },
{ value: "GA", label: "Gabon" },
{ value: "GM", label: "Gambia The" },
{ value: "GE", label: "Georgia" },
{ value: "DE", label: "Germany" },
{ value: "GH", label: "Ghana" },
{ value: "GI", label: "Gibraltar" },
{ value: "GR", label: "Greece" },
{ value: "GL", label: "Greenland" },
{ value: "GD", label: "Grenada" },
{ value: "GP", label: "Guadeloupe" },
{ value: "GU", label: "Guam" },
{ value: "GT", label: "Guatemala" },
{ value: "XU", label: "Guernsey and Alderney" },
{ value: "GN", label: "Guinea" },
{ value: "GW", label: "Guinea-Bissau" },
{ value: "GY", label: "Guyana" },
{ value: "HT", label: "Haiti" },
{ value: "HM", label: "Heard and McDonald Islands" },
{ value: "HN", label: "Honduras" },
{ value: "HK", label: "Hong Kong S.A.R." },
{ value: "HU", label: "Hungary" },
{ value: "IS", label: "Iceland" },
{ value: "IN", label: "India" },
{ value: "ID", label: "Indonesia" },
{ value: "IR", label: "Iran" },
{ value: "IQ", label: "Iraq" },
{ value: "IE", label: "Ireland" },
{ value: "IL", label: "Israel" },
{ value: "IT", label: "Italy" },
{ value: "JM", label: "Jamaica" },
{ value: "JP", label: "Japan" },
{ value: "XJ", label: "Jersey" },
{ value: "JO", label: "Jordan" },
{ value: "KZ", label: "Kazakhstan" },
{ value: "KE", label: "Kenya" },
{ value: "KI", label: "Kiribati" },
{ value: "KP", label: "Korea North" },
{ value: "KR", label: "Korea South" },
{ value: "KW", label: "Kuwait" },
{ value: "KG", label: "Kyrgyzstan" },
{ value: "LA", label: "Laos" },
{ value: "LV", label: "Latvia" },
{ value: "LB", label: "Lebanon" },
{ value: "LS", label: "Lesotho" },
{ value: "LR", label: "Liberia" },
{ value: "LY", label: "Libya" },
{ value: "LI", label: "Liechtenstein" },
{ value: "LT", label: "Lithuania" },
{ value: "LU", label: "Luxembourg" },
{ value: "MO", label: "Macau S.A.R." },
{ value: "MK", label: "Macedonia" },
{ value: "MG", label: "Madagascar" },
{ value: "MW", label: "Malawi" },
{ value: "MY", label: "Malaysia" },
{ value: "MV", label: "Maldives" },
{ value: "ML", label: "Mali" },
{ value: "MT", label: "Malta" },
{ value: "XM", label: "Man (Isle of)" },
{ value: "MH", label: "Marshall Islands" },
{ value: "MQ", label: "Martinique" },
{ value: "MR", label: "Mauritania" },
{ value: "MU", label: "Mauritius" },
{ value: "YT", label: "Mayotte" },
{ value: "MX", label: "Mexico" },
{ value: "FM", label: "Micronesia" },
{ value: "MD", label: "Moldova" },
{ value: "MC", label: "Monaco" },
{ value: "MN", label: "Mongolia" },
{ value: "MS", label: "Montserrat" },
{ value: "MA", label: "Morocco" },
{ value: "MZ", label: "Mozambique" },
{ value: "MM", label: "Myanmar" },
{ value: "NA", label: "Namibia" },
{ value: "NR", label: "Nauru" },
{ value: "NP", label: "Nepal" },
{ value: "AN", label: "Netherlands Antilles" },
{ value: "NL", label: "Netherlands The" },
{ value: "NC", label: "New Caledonia" },
{ value: "NZ", label: "New Zealand" },
{ value: "NI", label: "Nicaragua" },
{ value: "NE", label: "Niger" },
{ value: "NG", label: "Nigeria" },
{ value: "NU", label: "Niue" },
{ value: "NF", label: "Norfolk Island" },
{ value: "MP", label: "Northern Mariana Islands" },
{ value: "NO", label: "Norway" },
{ value: "OM", label: "Oman" },
{ value: "PK", label: "Pakistan" },
{ value: "PW", label: "Palau" },
{ value: "PS", label: "Palestinian Territory Occupied" },
{ value: "PA", label: "Panama" },
{ value: "PG", label: "Papua new Guinea" },
{ value: "PY", label: "Paraguay" },
{ value: "PE", label: "Peru" },
{ value: "PH", label: "Philippines" },
{ value: "PN", label: "Pitcairn Island" },
{ value: "PL", label: "Poland" },
{ value: "PT", label: "Portugal" },
{ value: "PR", label: "Puerto Rico" },
{ value: "QA", label: "Qatar" },
{ value: "RE", label: "Reunion" },
{ value: "RO", label: "Romania" },
{ value: "RU", label: "Russia" },
{ value: "RW", label: "Rwanda" },
{ value: "SH", label: "Saint Helena" },
{ value: "KN", label: "Saint Kitts And Nevis" },
{ value: "LC", label: "Saint Lucia" },
{ value: "PM", label: "Saint Pierre and Miquelon" },
{ value: "VC", label: "Saint Vincent And The Grenadines" },
{ value: "WS", label: "Samoa" },
{ value: "SM", label: "San Marino" },
{ value: "ST", label: "Sao Tome and Principe" },
{ value: "SA", label: "Saudi Arabia" },
{ value: "SN", label: "Senegal" },
{ value: "RS", label: "Serbia" },
{ value: "SC", label: "Seychelles" },
{ value: "SL", label: "Sierra Leone" },
{ value: "SG", label: "Singapore" },
{ value: "SK", label: "Slovakia" },
{ value: "SI", label: "Slovenia" },
{ value: "XG", label: "Smaller Territories of the UK" },
{ value: "SB", label: "Solomon Islands" },
{ value: "SO", label: "Somalia" },
{ value: "ZA", label: "South Africa" },
{ value: "GS", label: "South Georgia" },
{ value: "SS", label: "South Sudan" },
{ value: "ES", label: "Spain" },
{ value: "LK", label: "Sri Lanka" },
{ value: "SD", label: "Sudan" },
{ value: "SR", label: "Suriname" },
{ value: "SJ", label: "Svalbard And Jan Mayen Islands" },
{ value: "SZ", label: "Swaziland" },
{ value: "SE", label: "Sweden" },
{ value: "CH", label: "Switzerland" },
{ value: "SY", label: "Syria" },
{ value: "TW", label: "Taiwan" },
{ value: "TJ", label: "Tajikistan" },
{ value: "TZ", label: "Tanzania" },
{ value: "TH", label: "Thailand" },
{ value: "TG", label: "Togo" },
{ value: "TK", label: "Tokelau" },
{ value: "TO", label: "Tonga" },
{ value: "TT", label: "Trinidad And Tobago" },
{ value: "TN", label: "Tunisia" },
{ value: "TR", label: "Turkey" },
{ value: "TM", label: "Turkmenistan" },
{ value: "TC", label: "Turks And Caicos Islands" },
{ value: "TV", label: "Tuvalu" },
{ value: "UG", label: "Uganda" },
{ value: "UA", label: "Ukraine" },
{ value: "AE", label: "United Arab Emirates" },
{ value: "GB", label: "United Kingdom" },
{ value: "US", label: "United States" },
{ value: "UM", label: "United States Minor Outlying Islands" },
{ value: "UY", label: "Uruguay" },
{ value: "UZ", label: "Uzbekistan" },
{ value: "VU", label: "Vanuatu" },
{ value: "VA", label: "Vatican City State (Holy See)" },
{ value: "VE", label: "Venezuela" },
{ value: "VN", label: "Vietnam" },
{ value: "VG", label: "Virgin Islands (British)" },
{ value: "VI", label: "Virgin Islands (US)" },
{ value: "WF", label: "Wallis And Futuna Islands" },
{ value: "EH", label: "Western Sahara" },
{ value: "YE", label: "Yemen" },
{ value: "YU", label: "Yugoslavia" },
{ value: "ZM", label: "Zambia" },
{ value: "ZW", label: "Zimbabwe" }
];
const handleChangeOption = () => {
return setSelectedOption;
}
useEffect(() => {
if (selectedOption.value) {
console.log(selectedOption)
setNgonNgu({ ...ngonNgu, translate_list: selectedOption.value })
}
}, [selectedOption])
{console.log(selectedOption)}
return (
<Select className={`col-12 o-languages`}
isMulti
value={ngonNgu.translate_list ? { value: ngonNgu.translate_list, label: ngonNgu.translate_list } : { value: "Chọn những ngôn ngữ dịch", label: "Chọn những ngôn ngữ dịch" }}
onChange={handleChangeOption()}
options={options} />
)
}
const handleSubmit = () => {
let arr = [{
nameLanguage: ngonNgu.language_name,
mainLanguage: ngonNgu.main_lang,
titleLanguage: ngonNgu.title_lang,
descriptionLanguage: ngonNgu.describe_lang,
authorLanguage: ngonNgu.author_lang,
rateLanguage: ngonNgu.rate_lang,
reviewsLanguage: ngonNgu.reviews_lang,
transLanguage: ngonNgu.translate_list
}]
ajaxCallPost(`save-lang`, arr).then(rs => {
resetData()
handleGetLanguage();
Const_Libs.TOAST.success("Thêm thành công")
})
}
const resetData = () => {
setNgonNgu({
language_name: '',
main_lang: '',
title_lang: '',
describe_lang: '',
author_lang: '',
rate_lang: '',
reviews_lang: '',
translate_list: []
})
}
return (
<>
<button type="button" className="btn btn-primary" data-bs-toggle="modal" data-bs-target="#myModalAddNgonNgu" style={{ fontSize: '14px' }}>
Thêm
</button>
<div>
<div className="modal fade" id="myModalAddNgonNgu">
<div className="modal-dialog modal-dialog-centered" style={{ minWidth: '700px' }}>
<div className="modal-content">
<div className="modal-header">
<h4 className="modal-title">Thêm ngôn ngữ</h4>
<button type="button" className="btn-close" data-bs-dismiss="modal" />
</div>
<div className="modal-body">
<form>
<div className="col">
<div className="row-2">
<label htmlFor="name-campaign" className="form-label fs-6 fw-bolder">Tên ngôn ngữ</label>
<input type="text"
className="form-control" id="name-campaign"
placeholder="Nhập tên ngôn ngữ...."
value={ngonNgu.language_name}
onChange={(e) => setNgonNgu({ ...ngonNgu, language_name: e.target.value })}
/>
</div>
<div className="row-2">
<label htmlFor="name-campaign" className="form-label fs-6 fw-bolder">Tiêu đề</label>
<input type="text"
className="form-control" id="name-campaign"
placeholder="Nhập tiêu đề...."
value={ngonNgu.title_lang}
onChange={(e) => setNgonNgu({ ...ngonNgu, title_lang: e.target.value })}
/>
</div>
<div className="row-2">
<label htmlFor="name-campaign" className="form-label fs-6 fw-bolder">Mô tả</label>
<input type="text"
className="form-control" id="name-campaign"
placeholder="Nhập mô tả...."
value={ngonNgu.describe_lang}
onChange={(e) => setNgonNgu({ ...ngonNgu, describe_lang: e.target.value })}
/>
</div>
<div className="row-2">
<label htmlFor="name-campaign" className="form-label fs-6 fw-bolder">Tác giả</label>
<input type="text"
className="form-control" id="name-campaign"
placeholder="Nhập tác giả (VD: Author)"
value={ngonNgu.author_lang}
onChange={(e) => setNgonNgu({ ...ngonNgu, author_lang: e.target.value })}
/>
</div>
<div className="row-2">
<label htmlFor="name-campaign" className="form-label fs-6 fw-bolder">Đánh giá</label>
<input type="text"
className="form-control" id="name-campaign"
placeholder="Nhập đánh giá (VD: Rate)"
value={ngonNgu.rate_lang}
onChange={(e) => setNgonNgu({ ...ngonNgu, rate_lang: e.target.value })}
/>
</div>
<div className="row-2">
<label htmlFor="name-campaign" className="form-label fs-6 fw-bolder">Lượt đánh giá</label>
<input type="text"
className="form-control" id="name-campaign"
placeholder="Nhập lượt đánh giá (VD: reviews)"
value={ngonNgu.reviews_lang}
onChange={(e) => setNgonNgu({ ...ngonNgu, reviews_lang: e.target.value })}
/>
</div>
</div>
<div className="col">
<div className="row-2">
<label htmlFor="name-campaign" className="form-label fs-6 fw-bolder">Ngôn ngữ chính</label>
<SelectMainLanguage />
</div>
<div className="row-2">
<label htmlFor="name-campaign" className="form-label fs-6 fw-bolder">Những ngôn ngữ dịch</label>
<SelectTransLanguage />
</div>
</div>
</form>
</div>
<div className="modal-footer">
<button type="button" className="btn btn-success" data-bs-dismiss="modal" onClick={handleSubmit}>Submit</button>
<button type="button" className="btn btn-danger" data-bs-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
</div>
</>
);
}
export default ModalAddNgonNgu;
The backend is OK, so the problem is this thing. Can you show me the mistake? Thank you
You should never define a component inside another component.
Move both SelectMainLanguage and SelectTransLanguage out of ModalAddNgonNgu.
Then connect these two components and ModalAddNgonNgu with props.
Like this:
const ModalAddNgonNgu = (props) => {
const { handleGetLanguage } = props; ....
... rest of the component
} // end of ModalAddNgonNgu definition
function SelectTransLanguage({setNgonNgu}) { // setNgonNgu comes from ModalAddNgonNgu
const [selectedOption, setSelectedOption] = useState({}) ....
}

Set minimum height or width for column FusionCharts

If data is very lower than others, it's almost like zero, and the user can't click or hover because it's too small.
How can I set a minimum height or width for very small numbers?
I have this problem with ApexCharts too.
const chartConfigs = {
type: "column2d",
width: "100%",
height: 500,
dataFormat: "json",
dataSource: {
chart: {
caption: "Countries With Most Oil Reserves [2017-18]",
subCaption: "In MMbbl = One Million barrels",
xAxisName: "Country",
yAxisName: "Reserves (MMbbl)",
numberSuffix: "K",
theme: "fusion",
},
data: [
{
label: "Venezuela",
value: "290",
},
{
label: "Saudi",
value: "260",
},
{
label: "Canada",
value: "180",
},
{
label: "Iran",
value: "140",
},
{
label: "Russia",
value: "115",
},
{
label: "UAE",
value: "100",
},
{
label: "US",
value: "3000000",
},
{
label: "China",
value: "30",
},
],
},
};
This is normal since your y-axis scale is linear if one of your plots has a very large value & the other plot values are very low compared to the large plot value then the plot area of the smaller value plot will be very minimum.
To overcome this you can use logarithmic y-axis, here is an example -
FusionCharts.ready(function() {
var footfallChart = new FusionCharts({
type: 'logmscolumn2d',
renderAt: 'chart-container',
width: '500',
height: '300',
dataFormat: 'json',
dataSource: {
"chart": {
"theme": "fusion",
"caption": "Store footfall vs Online visitors ",
"subCaption": "Last Year",
"xAxisName": "Quarter",
"yAxisName": "No of visitors",
"showXAxisLine": "1",
"axisLineAlpha": "10"
},
"categories": [{
"category": [{
"label": "Q1"
},
{
"label": "Q2"
},
{
"label": "Q3"
},
{
"label": "Q4"
}
]
}],
"dataset": [{
"seriesname": "Total footfalls",
"data": [{
"value": "126734"
},
{
"value": "64"
},
{
"value": "34"
},
{
"value": "56"
},
{
"value": "78"
}
]
}]
}
}).render();
});
<script src="https://cdn.fusioncharts.com/fusioncharts/latest/fusioncharts.js"></script>
<script src="https://cdn.fusioncharts.com/fusioncharts/latest/themes/fusioncharts.theme.fusion.js"></script>
<div id="chart-container">FusionCharts will render here</div>

How can I add the first to the array in useState in React?

I have an array object called tempArr.
When I run a function called fetchLifeCycle, i want to act setPickerItems(tempArr); is mandatory first, and then setPickerItems([...tempArr, { label: 'Not selected', value: "NONE" }]) .
As a result, { label: 'not selected', value: "NONE" } was added at the end.
But I want to add that object to the first object of pickerItems. How do I do that?
this is my code
tempArr = [
{ label: "hi", value: 'egg' },
{ label: "bye", value: 'insect' },
{ label: "woo", value: 'pest' },
{ label: "pick", value: 'hambuger' },
]
const [pickerItems, setPickerItems] = useState([])
const fetchLifeCycle = () => {
setPickerItems(tempArr);
setPickerItems([...tempArr, { label: '선택안함', value: "NONE" }])
}
expected answer
pickerItems = [
{ label: '선택안함', value: "NONE" }
{ label: "hi", value: 'egg' },
{ label: "bye", value: 'insect' },
{ label: "woo", value: 'pest' },
{ label: "pick", value: 'hambuger' },
]
tempArr = [
{ label: "hi", value: 'egg' },
{ label: "bye", value: 'insect' },
{ label: "woo", value: 'pest' },
{ label: "pick", value: 'hambuger' },
]
const updated = [{ label: '선택안함', value: "NONE" }, ...tempArr]
console.log('updated', updated)
You just have to reverse the order:
setPickerItems([{ label: '선택안함', value: "NONE" }, ...tempArr])
You can put the new item first, then spread the existing array:
setPickerItems([{ label: '선택안함', value: "NONE" }, ...tempArr])
Just simple:
setPickerItems([{ label: '선택안함', value: "NONE" }, ...tempArr])

ReactJS and Material UI TreeView: Can I use a multi-level JSON/array of objects with different names to populate the TreeView?

I have an array of objects that is multi-leveled with different names that I need to populate a TreeView component :
export const application_group_one = [
{
id: uniqueId(),
name: "Application 1",
organizations: [
{
id: uniqueId(),
name: "Organization 1",
artifacts: [
{
id: uniqueId(),
name: "Artifact 1",
},
],
},
],
},
{
id: uniqueId(),
name: "Application 2",
organizations: [
{
id: uniqueId(),
name: "Organization 1",
artifacts: [],
},
],
},
];
export const application_group_two = [
{
id: uniqueId(),
name: "Application 3",
organizations: [
{
id: uniqueId(),
name: "Organization 1",
artifacts: [
{
id: uniqueId(),
name: "Artifact 1",
},
{
id: uniqueId(),
name: "Artifact 2",
},
{
id: uniqueId(),
name: "Artifact 3",
},
],
},
{
id: uniqueId(),
name: "Organization 2",
artifacts: [
{
id: uniqueId(),
name: "Artifact 1",
},
{
id: uniqueId(),
name: "Artifact 2",
},
{
id: uniqueId(),
name: "Artifact 3",
},
],
},
{
id: uniqueId(),
name: "Organization 3",
artifacts: [
{
id: uniqueId(),
name: "Artifact 1",
},
{
id: uniqueId(),
name: "Artifacy 2",
},
{
id: uniqueId(),
name: "Artifact 3",
},
],
},
{
id: uniqueId(),
name: "Organization 4",
artifacts: [
{
id: uniqueId(),
name: "Artifact 1",
},
{
id: uniqueId(),
name: "Artifact 2",
},
{
id: uniqueId(),
name: "Artifact 3",
},
],
},
],
},
];
I'm able to output the Organizations but not the artifacts. Having varying names for each children object is giving me a hard time. I would like a TreeView that can expand as many levels as I want with differing names for the nest objects. :
const getTreeItemsFromData = (treeItems) => {
return treeItems.map((treeItemData) => {
let organizations = undefined;
if (treeItemData.organizations && treeItemData.organizations.length > 0) {
organizations = getTreeItemsFromData(treeItemData.organizations);
}
return <TreeItem key={treeItemData.id} nodeId={treeItemData.id} label={treeItemData.name} children={organizations} />;
});
};
const DataTreeView = ({ treeItems }) => {
return (
<TreeView defaultCollapseIcon={<ExpandMoreIcon />} defaultExpandIcon={<ChevronRightIcon />}>
{getTreeItemsFromData(treeItems)}
</TreeView>
);
};
export const Tree = () => {
return (
<div className="App">
<DataTreeView treeItems={application_group_one} />
<br />
<DataTreeView treeItems={application_group_two} />
</div>
);
};

Difficulties to query nested arrays with multiple itens Mongoose

I`ve modeled a document to be:
let UserSchema = new Schema({
name: { type: String, required: true, max: 50, unique: true },
email: {type: String, required: true, max: 50, unique: true},
password: {type: String, required: true, max: 20},
monitoringProject: [
{
projectName: { type: String, required: true, max: 30},
token: { type: String, required: true},
dispositives: [
{
name: { type: String, required: true, max: 15},
value: { type: String, required: true},
token: { type: String}
}
]
}
],
controlProject: [
{
projectName: { type: String, required: true, max: 30},
token: { type: String, required: true},
dispositives: [
{
name: { type: String, required: true, max: 15},
value: { type: String, required: true},
token: { type: String}
}
]
}
]
});
In the monitoringProject, for example, I can log too many different projects, and, to each project, I can log too many dispositives. So, I have nested arrays. In other project, where I have just one project, and many dispositives, I can list them and search for just one dispositive. But in this case, like this:
[ { "_id": "5ee18ece1ea5af75bae55f91", "monitoringProject": [ { "dispositives": [ { "_id": "5ee18ef31ea5af75bae55f9c", "name": "Dispositivo 1", "token": "$2b$15$NntmY9ihNZ7R1Vg1WMtmzOSjlfCoKIuHLofF6g5tKXA57WLLc2At2" }, { "_id": "5ee18ef81ea5af75bae55f9e", "name": "Dispositivo 2", "token": "$2b$15$OZB7HbDLvonsv6A71ozW7.yVY2vJOipTCj0AH7XzoafQwwDho.jpm" }, { "_id": "5ee18efc1ea5af75bae55fa0", "name": "Dispositivo 3", "token": "$2b$15$0hpDzNeTO2qJzBVyAHc/UesrnIRi/YpeAlpCLewNhmfl6fe3SEN0i" }, { "_id": "5ee2278d0754817853134bf3", "name": "Dispositivo 4", "token": "$2b$15$ldC5/CyxITPJGUvtXJ.2S.D6a3FBftg6ctQeS4ne/9xpMP5PPiszK" }, { "_id": "5ee2288956fc4c7870044395", "name": "Dispositivo 6", "token": "$2b$15$3rJt.gXEi/gALvrwxVUsWuwF2RUcBmZcoFOQeXwF45ZuKQrB3AGHG" }, { "_id": "5ee6d23d1756b7a8384bcff0", "name": "Dispositivo 7", "token": "$2b$15$C3I9STKJpf9i/7hzhvHEs.IizXpOEmgRTD3hd7ZSdcvATb73Z0zNC" } ], "_id": "5ee18ede1ea5af75bae55f94", "projectName": "Projeto 2", "token": "$2b$15$xaytMbMnGd3BMAGapX8nn.imvkQKetqx0OIlUUyP3gCxlKz/G6DiG" } ] } ]
I can only list all the Dispositives. I want to return just, for example, "Dispositivo 2".
I used to querys:
await User.find({ email: req.body.email, monitoringProject: { $elemMatch: { token: req.body.projecttoken, dispositives: { $elemMatch: { token: req.body.dispositivetoken } } } } }, { "monitoringProject.$.dispositives": 1} )
or
await User.find({ email: req.body.email, 'monitoringProject.token': req.body.projecttoken, 'monitoringProject.dispositives.token': req.body.dispositivetoken}, { 'monitoringProject.dispositives.$': 1 })
Using find or findOne. How can I return just the document I want? I tried so many different ways, but with no lucky.

Resources