C
C
campus12018-08-25 19:15:21
JavaScript
campus1, 2018-08-25 19:15:21

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"}
}

I need to render data by type:
Language - English
Sex - Male
Height - 170cm

How I tried to solve:
Make data preset -
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" }
];

And then the function for rendering
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>
      );
    });
  };

Everything seems to be working, but during the initial rendering, a red window with text flies out for 2-3 seconds can not read label of undefined, then everything is rendered normally
5b81818308586688361228.pngQuestions:
  1. How can the original error be corrected?
  2. Did I choose the normal approach and is the function readable? TLDR : Is the code okay? :)

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Anton Spirin, 2018-08-25
@campus1

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';
});

For the floor, you can not do a function at all
<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 question

Ask a Question

731 491 924 answers to any question