I'm learning Nextjs. Getting this error while trying to fetch data from a firestore in dynamic pages ~ "[].js".
replace is a method used to transform the address prop in the EventLogistics component used below.
import { getAllEvents, getEventById } from "../../../helpers/api-util.js"
function EventDetailPage(props) {
const { event } = props;
if (!event) {
return (
<ErrorAlert>
<p>No event found</p>
</ErrorAlert>
);
}
return (
<Fragment>
<EventSummary title={event.title} />
<EventLogistics
key={event.id}
date={event.date}
address={event.location}
image={event.image}
imageAlt={event.title}
/>
<EventContent>
<p>{event.description}</p>
</EventContent>
</Fragment>
);
}
export async function getStaticProps(context) {
const eventId = context.params.eventId;
console.log(eventId);
const event = await getEventById(eventId);
return {
props: {
event: event,
},
revalidate: 3600,
};
}
export async function getStaticPaths() {
const events = await getAllEvents();
const paths = events.map((event) => ({ params: { eventId: event.id } }));
return {
paths: paths,
fallback: 'blocking',
};
}
In api-util.js. I have few helper functions to fetch the data. Below is the code. kindly help
export async function getAllEvents() {
const response = await fetch(
"https://next-events-4a68f-default-rtdb.firebaseio.com/events.json"
);
const data = await response.json();
const events = [];
for (const key in data) {
events.push({
id: key,
...data[key]
});
}
return events;
}
export async function getFeaturedEvents() {
const events = await getAllEvents();
return events.filter((event) => event.isFeatured);
}
export async function getEventById(id) {
const allEvents = await getAllEvents();
return allEvents.filter((event) => event.id === id);
}`
Below is the code of EventLogistics component where the replace method is used on the props recieved
export default function EventLogistics(props) {
const { date, address, image, imageAlt } = props;
const humanReadableDate = new Date(date).toLocaleDateString('en-US', {
day: 'numeric',
month: 'long',
year: 'numeric',
});
const addressText = address.replace(', ', '\n');
return (
{/* renders a card with the props above */}
);
}
TIA!