Issue
Some of my codes are repeating like tutor.bla bla. What's the best practice for the code block below? How to destructure tutor
object?
const Tutors = ({ tutors }) => {
return (
<div>
{tutors.map((tutor) => (
<TutorListingCard
key={tutor.id}
image={tutor.attributes.profile_photo.data.attributes.url}
name={tutor.attributes.name}
surname={tutor.attributes.surname}
university={tutor.attributes.university}
services={tutor.attributes.services.data.map((service) => {
return service.attributes.name;
})}
students_helped={tutor.attributes.students_helped.data.length}
rating={Number.isNaN(getRating(tutor)) ? 0 : getRating(tutor)}
reviews={tutor.attributes.reviews.data.length}
biography={tutor.attributes.biography}
subjects={tutor.attributes.subjects.data.map((subject) => {
return subject.attributes.name;
})}
price={tutor.attributes.price}
/>
))}
</div>
);
};
Solution
You can:
- Destructure tutor object and then instead of
tutor.attributes
use justattributes
. - Not use a function with only return in it where you can just return the value
services={attributes.services.data.map((service) => service.attributes.name)}
So final code would be:
const Tutors = ({ tutors }) => (
<div>
{tutors.map((tutor) => {
const { attributes } = tutor;
return (
<TutorListingCard
key={tutor.id}
image={attributes.profile_photo.data.attributes.url}
name={attributes.name}
surname={attributes.surname}
university={attributes.university}
services={attributes.services.data.map((service) => service.attributes.name}
students_helped={attributes.students_helped.data.length}
rating={Number.isNaN(getRating(tutor)) ? 0 : getRating(tutor)}
reviews={attributes.reviews.data.length}
biography={attributes.biography}
subjects={attributes.subjects.data.map((subject) => subject.attributes.name)}
price={attributes.price}
/>
);
})}
</div>
);
This is the most basic thing. Aside from that your component TutorListingCard could also have a data property where you would pass all that information as an object. But unless you are passing an array (which you are not), I'd probably not go that way.
Meaning:
{
tutors.map((tutor) =>
<TutorListingCard
key={tutor.id}
data={tutor}
/>
}
Answered By - MalwareMoon
Answer Checked By - - Dawn Plyler (ReactFix Volunteer)