i want to fetch a single post from a lis of posts, i already set up individual links for each post in the api
views.py
@api_view(['GET'])
def Post_detail(request,pk):
try:
post_detail = Post.objects.get(pk=pk)
except post_detail.DoesNotExist:
return JsonResponse({'message': 'The Post does not exist'}, status=status.HTTP_404_NOT_FOUND)
Post_serializer = PostSerializer(post_detail)
return JsonResponse({'data': Post_serializer.data})
i don't know how to actually fetch it on react, how do i get the id?
async componentDidMount() {
const response = await fetch('/api/Post' + id);
const data = await response.json();
this.setState({
post: data,
loading: false
});
}
i am also open to using axios.
What you are doing is correct, you will need to put a /
after /api/Post
, so that the endpoint is correct.
async componentDidMount() {
const response = await fetch('/api/Post/' + id);
const data = await response.json();
this.setState({
post: data,
loading: false
});
}
With axios, it would look something like this (you could also use async/await
if you like):
componentDidMount() {
axios.get('/api/Post/' + id).then((response) => {
this.setState({
post: response.data,
loading: false
}).catch((error) => {
console.log(error);
});
})
}
Usually, id
is added as part of URL www.test.com/post/id
In React with react-router-dom
import { Route } from 'react-router-dom';
<Route exact path="/post/:id" component={Article} />
Then you can get parameter on your page where u have to fetch data with id
const {id} = useParams();
and do const response = await fetch('/api/Post/' + id);
Btw i recommend you to use React hooks
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.