Get slug and fetch data #13729
-
Bug reportDescribe the bugI wanted to use a slug to fetch an api with it and return the result. I tried to use Server-side rendering and react component but the data doesn't appear on the page (It's not invisible or something). The Layout is rendered but everything else not. I don't know this is my fault or a bug. To Reproduce
Expected behaviorThe json data from the api should appear on the page. System information
|
Beta Was this translation helpful? Give feedback.
Answered by
jamesmosier
Jun 4, 2020
Replies: 1 comment 1 reply
-
Hi @JuzouSatoru2 In order to do this, you'd need to do something like this instead: import React from 'react';
import axios from 'axios';
import { useRouter } from 'next/router'
import Layout from '../../../components/Layout';
function Edit() {
const [post, setPost] = React.useState(null);
const router = useRouter();
const { slug } = router.query;
// useEffect will run on each render only if the `slug` changes,
// so on initial render once `useRouter` has the query then it'll run the effect
React.useEffect(() => {
// fetchData runs async, so whenever the response comes back
// then you can set some state, in this case `setPost(data)`
const fetchData = async () => {
const response = await axios.get(`api/blog/${slug}`)
const data = await response.json();
// you may need to do `setPost(data.data)` depending on how your API returns the information
setPost(data);
};
// once you have the slug, call `fetchData`
if (slug) {
fetchData();
}
}, [slug]);
return (
<Layout>
{post ? post.title : null}
</Layout>
)
} |
Beta Was this translation helpful? Give feedback.
1 reply
Answer selected by
alex289
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hi @JuzouSatoru2
In order to do this, you'd need to do something like this instead: