I am developing learning module in My React native app. So, i have this type of JSON response from firebase.
[
{
"description": "Desc How Should Companies Get Started in Data Science?",
"type": "section",
"title": "How Should Companies Get Started in Data Science?",
"section": "2",
"lesson": "3",
"categoryId": "621KeXergbNg690pECx6"
},
{
"lesson": "2",
"description": "Desc What is Hadoop?",
"title": "What is Hadoop?",
"section": "2",
"type": "section",
"categoryId": "A7IC1AliDVnvZECcU5oB"
},
{
"description": "Desc How Big Data is Driving Digital Transformation",
"lesson": "2",
"type": "section",
"title": "How Big Data is Driving Digital Transformation",
"section": "3",
"categoryId": "JNK9qIKIKW8gvXvWJ19w"
},
]
and My Design is:
So how to achieve this. Thanks in advance.
CodePudding user response:
the response should be structured better but to answer your question you can form an array of lessons that include sections by using this logic
const groupByLesson = (arr) => {
const array = [];
return arr.reduce((memo, x) => {
const lessonIndex = memo.findIndex(
(obj) => obj?.lessonNumber == x.lesson
);
if (lessonIndex == -1) {
memo.push({ lessonNumber: x.lesson, sections: [x] });
} else {
const sortedSections = [...memo[lessonIndex].sections,x]
.sort((a, b) => a.section > b.section);
memo[lessonIndex].sections = sortedSections
}
return memo;
}, []);
}
const lessonsArray = groupByLesson(response).sort(
(a, b) => a.lessonNumber > b.lessonNumber
);
then you can use this array inside your function by mapping it to some ui components like this, (made some quick and dirty ui just to show you an example)
const [showSections, setShowSections] = useState();
{lessonsArray.map((lesson) => (
<View
key={lesson.lessonNumber}
style={{ marginBottom: 20, borderWidth: 2, width: "100%" }}
>
<View
style={{
flexDirection: "row",
justifyContent: "space-between",
}}
>
<Text>{"Lesson " lesson.lessonNumber}</Text>
<Pressable
onPress={() => {
setShowSections(lesson.lessonNumber);
}}
>
<Text style={{ fontSize:20, marginRight:20}}>{">"}</Text>
</Pressable>
</View>
{showSections == lesson.lessonNumber &&
lesson.sections.map((section) => (
<>
<Text>{"Section " section.section}</Text>
<Text>{section.title}</Text>
</>
))}
</View>
))}