I need to share some data I have collected with useState from one component file to another. I am building a blog using Material UI that displays all posts on the home page. When a specific post is clicked I want to redirect the user to a single post page where they can read the entire thing. I have searched StackOverflow and the internet and can't seem to find a straight forward answer to the problem. I think context API might be overkill. And I am unsure how to pass props from one component to another when I am not calling the function in the other component file.
This is part of the home page component. This code stores the post id that I need to access from the SinglePost component. When I click a post it correctly console.logs the id:
export default function HomeCard() {
const [latestPosts, setLatestPost] = useState([]);
useEffect(() => {
fetch('http://localhost:8000/posts')
.then ((res) => {
return res.json();
})
.then ((data) => {
setLatestPost(data.reverse());
});
}, []);
const navigate = useNavigate();
const storePostId = (singlePostId) => {
navigate('/single-post')
console.log(singlePostId);
}
A little further down in the file:
<CardActionArea
onClick={ () =>
storePostId(latestPost.id)
}>
Within my SinglePost component:
const SinglePost = () => {
useEffect(() => {
fetch(`http://localhost:8000/posts/${singlePostId}`)
.then ((res) => {
return res.json();
})
.then ((data) => {
return (data);
});
}, []);