I am new to react and a question on how to handle empty arrays. I have some data on a specific class. The class data can be seen below. I am trying to display the data in my web app but I have having trouble with the logic of mapping array when they are empty.
a simplified version of my code is shown below:
import React from 'react';
import { useState, useEffect } from "react";
const data = {
ece1004: {
number: "ECE 1004",
name: "Introduction to ECE Concepts",
des: "Introduction to topics that span the field of electrical and computer engineering (ECE). Content presented through the lens of application with accompanying hands-on exercises. Basics of circuits, op-amps, power supplies, computer logic, system decomposition, and coding. Modeling and application of engineering professionalism. Exploration of ECE in society.",
pre: [["ENGE 1215", "ECE 1414"]],
co: [],
minGrade: "C",
offering: ["Fall", "Spring", "Summer"],
}
};
function ECE1004() {
const [data, setData] = useState([]);
const fetchClassObj = () => {
setData(data);
}
useEffect(() => {
fetchClassObj();
},[]);
return (
<>
<div>
{data.co ?
data.co.map(coreq => {
return(
<div className="classDes">
Coreqs: {coreq.join(', ')}
</div>
)
}) : <h3>No data yet</h3> }
</div>
</>
)
}
export default ECE1004
I would like the class data to be displayed all in separate divs. For example, if I wrote the same code for the prereqs, it would display as “Prereqs: ECE 1215, ECE 1414” with a comma inbetween (hence the .join(', ')
function).
However, since the co member of the data is empty the mapping function is not recognized. I was wondering what the logic is to check if the array is empty as well as use the .join(', ')
function.
I have tried not mapping the data and using {data.co.length ? 'coreqs' + data.co.join(', ') : 'coreqs: None'}
but then the .join(', ')
is not recognized.
Any help would be appreciated, thank you.