I'm trying to pass an id through state in a react router v6 link, because I need it in another components that uses that specific ID to make an GET request.
This is the code where the Link is.
import React from "react"
import { Link } from "react-router-dom";
const Post = ({id, title}) => {
return (
<div key={id} className="col-sm-12 col-lg-6 d-flex justify-content-center">
<div className="card d-flex">
<h3 className="card-title">{title}</h3>
<Link
to="/PostDetail"
state= {id}
>
Detalles</Link>
</div>
</div>
)
}
export default Post;
This is where the link navigates to (the link works, but the state is undefined)
import React, {useState, useEffect} from "react"
import { useLocation } from "react-router";
const PostDetail = () => {
const [post, setPost] = useState([]);
const [loading, setLoading] = useState(true);
const location = useLocation();
const id = location.state;
const url = `https://jsonplaceholder.typicode.com/posts/${id}`
const getPostDetail = async () => {
fetch(url)
.then((res)=>{
res.json()
})
.then((res)=>{
console.log(res)
setLoading(false)
})
.catch(e=>console.log(e))
}
useEffect(()=>{
getPostDetail();
}, [])
return (
<div>
<h1>hola</h1>
{loading ? <h3>loading...</h3> : <div>{post}</div>}
</div>
)
}
export default PostDetail;
The "id" is correct in the "Post" component, I have checked already.
The routing is not the issue, since the Links redirects correctly to "PostDetail" and the "loading..." text appears, but then it disappears and the console shows https://jsonplaceholder.typicode.com/posts/[object Object]