Below is a React useEffect hook I used in my application, basically what it does is:
data
is an array for objects such as {round:number, date:dateString}
.
When the application starts running, data
will be an empty array, whenever round
gets updated, the useEffect()
will be called:
- if the
data
array is empty, we update it with its very first object. - else the
data
array is not empty and if the last object of data array has its date property equal toprops.localeDate
, I make a new array with the its last object updated - else the data array is not empty and else the last object's date property is not equal to
props.localeDate
, I append a new object to data array.
const Chart = ({ round, dateAndTime }) => {
const [data, setData] = useState([]);
const localeDate = dateAndTime.toLocaleDateString();
useEffect(() => {
if (data.length === 0) {
setData([
...data,
{
round: round,
date: localeDate,
},
]);
} else {
//update item if date matches
if (data[data.length - 1].date === localeDate) {
let newData = data.map((item) => {
let newItem =
item.date === localeDate ? { ...item, round: round } : item;
return newItem;
});
setData(newData);
} else {
setData([...data, { round: round, date: localeDate }]);
}
}
}, [round]);
return (jsx element);
}
My code works as expected, but I am wondering if there is any way to improve on it? Using if-else looks really ugly.