Reputation: 207
I'm trying to call API when I'm in the page that show data for the specific Profile.
The url looks like: localhost:8000/profile/223
API also require to be called api/profile/223
The way that I'm trying to call the API is:
const ProfileLayout = () => {
const [profileId, setProfileId] = useState();
useEffect(() => {
fetch('api/profile/id')
.then(result => {
setProfileId(result.id);
});
}, [id])
};
Upvotes: 2
Views: 472
Reputation: 20924
Fetch requires you to return the format of data from the Response object before you can use the data. Use response.json()
to get the JSON from your request.
And like @Adriana6 mentioned, add the /
to the start of your URL.
Use the profileId
to inject the value into the URL string.
useEffect(() => {
fetch('/api/profile/${profileId}')
.then(response => response.json())
.then(result => {
setProfileId(result.id);
});
}, []);
I don't have a lot of experience in React.js but learned how to do this by reading this article on how to make fetch
requests with React Hooks. I suggest that you look into it as well.
Upvotes: 2
Reputation: 1354
Please write the full url like localhost:8000/profile/${id}
in your fetch function parameter. Then parse it as json.
On the other hand, you don't have any id field. So, using id in you useEffect will not be triggered at all. If you want it to be triggered on page load then use
useEffect(() => {
// fetch
}, [])
instead of
useEffect(() => {
// fetch
}, [id])
Or you can change id
with profileId
. In that case, you have to check if profileId
is truthy (not null) before fetchin profile data
Upvotes: 1