"Why is the object passed through Link state in React undefined when accessed via useLocation on the next page?"
I'm having trouble passing an object through the Link state in React Router, and it's coming up as undefined when I try to access it on the next page using useLocation. Here’s a breakdown of my setup and the issues I'm encountering.
- Staff Component (Staff.js)
I'm fetching staff data from an API and rendering it with React Router's Link:
import React, { useEffect, useState } from 'react';
import { Link } from 'react-router-dom';
const Staff = () => {
const [staffMembers, setStaffMembers] = useState([]);
useEffect(() => {
// Fetch staff data from API
fetch('https://api.example.com/staff')
.then(response => response.json())
.then(data => setStaffMembers(data))
.catch(error => console.error('Error fetching staff:', error));
}, []);
return (
<div className="hidden p-5 md:grid md:grid-cols-4 gap-6">
{staffMembers.map((staff) => (
<Link
key={staff.id}
to={{
pathname: `/staff/${staff.title.replace(/\s+/g, '-')}`,
state: { staff } // Pass the entire staff object here
}}
className="image-div shadow hover:shadow-lg text-center rounded flex flex-col items-center border-l-8 border-yellow-200 p-3"
>
{staff.title_logo ? (
<img src={staff.title_logo} alt={staff.title} className="w-16 h-16" />
) : (
<div className="w-16 h-16 bg-gray-300 flex items-center justify-center">
<span>No Logo Available</span>
</div>
)}
<span className='mb-2 font-semibold text-lg'>{staff.title}</span>
</Link>
))}
</div>
);
};
export default Staff;
- Staff Detail Component (StaffDetail.js)
I’m trying to access the passed staff object using useLocation:
import React from 'react';
import { useLocation } from 'react-router-dom';
const StaffDetail = () => {
const location = useLocation();
const staff = location.state?.staff; // Attempt to access the staff object
console.log('Location:', location); // Log the entire location object
console.log('Staff:', staff); // Check what is logged here
if (!staff) {
return <div>No staff member data available. Please navigate from the staff list.</div>;
}
return (
<div>
<h1>{staff.title}</h1>
{/* Render other staff details */}
</div>
);
};
export default StaffDetail;
Issues: 1.Undefined Staff Object: When navigating to the StaffDetail component, staff is undefined, even though it should be passed through the Link state. 2.Direct URL Navigation: I have confirmed that I'm not directly entering the URL in the address bar, which I understand would lead to state being undefined. 3.Logging the Location: I’ve logged the location object and found that location.state is null when I expect it to be populated with the staff object.