Answer the question
In order to leave comments, you need to log in
How to remove the error and is the code normal ??
Hello.
I get this object from the backend:
const data = {
q_lang: {value: 1},
q_sex: {value: 2},
q_height: {value: "170cm"}
}
Language - English
Sex - Male
Height - 170cm
const profileTitles = [
{
title: "Language of questions",
key: "q_lang",
dataByValue: [
{ value: 1, label: "English" },
{ value: 2, label: "Swedish" }
]
},
{
title: "Sex",
key: "q_sex",
dataByValue: [{ value: 1, label: "Male" }, { value: 2, label: "Female" }]
},
{ title: "Height", key: "q_height" }
];
renderProfileData = testingReducer => {
return profileTitles.map((element, index) => {
const questionValue = get(testingReducer, `${element.key}.value`); // get с lodash
let labelValue; // нужный нам label для рендеринга
if (element.hasOwnProperty("dataByValue")) {
const filteredDataByQuestionValue = element.dataByValue.filter(
el => el.value === questionValue
); // фильтрация по value
labelValue = filteredDataByQuestionValue[0].label;
} else {
labelValue = questionValue;
}
return (
<div className="profile-data">
<span>{element.title}</span>
<span>{labelValue}</span>
</div>
);
});
};
can not read label of undefined
, then everything is rendered normally Answer the question
In order to leave comments, you need to log in
You complicate the implementation where it is not required.
Everything can be made much clearer and easier:
const mapLangTitleByCode = code => ({
const titles = {
1: 'English',
2: 'Russian',
};
return titles[code] || 'unknown code';
});
<div className="profile-data">
<span>Language</span>
<span>{mapLangTitleByCode(data.q_lang)}</span>
</div>
<div className="profile-data">
<span>Sex</span>
<span>{data.q_sex === 1 ? 'Male' : 'Female'}</span>
</div>
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question