I'm trying to get the id from the URL, so I can get a specific post from the API, in order to return it. I can't use Class Component to do so, because useParams only works with functions. I try to put the data inside the variable post, but it also didn't work.
import { useParams } from "react-router-dom";
import axios from "axios";
const Post = () => {
let params = useParams();
let post = null;
axios.get('https://jsonplaceholder.typicode.com/posts/' + params.post_id)
.then(res => {
post = res.data ? (
<div>
<h4>{res.data.title}</h4>
<p>{res.data.body}</p>
</div>
) : (
<div>Loading post...</div>
);
});
return (
<div>{post}</div>
)
}
export default Post