I’ve been going through react-router’s tutorial, and I’ve been following it to the letter as far as I’m aware. I’m having some issues with the url params in loaders segment.
The static contact code looks like this
export default function Contact() {
const contact = {
first: "Your",
last: "Name",
avatar: "https://placekitten.com/g/200/200",
twitter: "your_handle",
notes: "Some notes",
favorite: true,
}
And when it loads, it looks like this. That works just fine, however, the tutorial then tells me to change that code so that I use data that’s loaded in instead. The code now looks like this
import { Form, useLoaderData } from "react-router-dom";
import {getContact} from "../contacts"
export async function loader({ params }){
const contact = await getContact(params.contactid);
return {contact}
}
export default function Contact() {
const {contact} = useLoaderData();
According to the tutorial, it should just load in an empty contact that looks like this but instead, every time I try to open one of the new contacts, it kicks up an error saying
React Router caught the following error during render TypeError: contact is null
The actual line of code this error points to is in the return segment of the contact component, which looks like this
return (
<div id="contact">
<div>
<img
key={contact.avatar}
src={contact.avatar || null}
/>
</div>
<div>
<h1>
{contact.first || contact.last ? (
<>
{contact.first} {contact.last}
</>
) : (
<i>No Name</i>
)}{" "}
<Favorite contact={contact} />
</h1>
{contact.twitter && (
<p>
<a
target="_blank"
href={`https://twitter.com/${contact.twitter}`}
>
{contact.twitter}
</a>
</p>
)}
{contact.notes && <p>{contact.notes}</p>}
<div>
<Form action="edit">
<button type="submit">Edit</button>
</Form>
<Form
method="post"
action="destroy"
onSubmit={(event) => {
if (
!confirm(
"Please confirm you want to delete this record."
)
) {
event.preventDefault();
}
}}
>
<button type="submit">Delete</button>
</Form>
</div>
</div>
</div>
);
}
Pretty much anywhere contacts is called gets an error. So, anyone have any idea what I’m doing wrong here? To my knowledge, I’ve been following their guide to the letter and it seems like it should be able to handle contacts not having any data, but it’s not.