简体   繁体   中英

API won't return data

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])
    };

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.

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

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM