I want to fetch an API, exported from module file data.js
I am getting this error "err SyntaxError: Unexpected token < in JSON at position 0"
The file below contains the API module
/**
* @typedef {object} PropertyType
* @property {string} label - The text to display
* @property {string} value - The enum value assigned
*/
/**
* Retrieve a list of all available property types.
*
* @returns {Promise<{ propertyTypes: PropertyType[] }>}
*/
async function getAvailablePropertyTypes() {
await wait(randomInteger(500));
return {
propertyTypes: [
{ label: 'Semi-detached', value: 'semi-detached' },
{ label: 'Detached house', value: 'detached' },
{ label: 'Terraced house', value: 'terraced' },
{ label: 'Flat', value: 'flat' },
]
};
}
export {getAvailablePropertyTypes};
The file below contains the imported API app.js
I think I am not fetching correctly at this line const response = await fetch(getAvailablePropertyTypes.propertyTypes)
How do I fetch from this function getAvailablePropertyTypes.propertyTypes??
import {getAvailablePropertyTypes} from './properties'
import { useEffect } from 'react'
function App() {
useEffect( async () => {
const response = await fetch(getAvailablePropertyTypes.propertyTypes)
const data = await response.json()
.then(res => {
console.log('res', res)
})
.catch(err => {
console.log('err', err)
})
}, [])
return (
<div className="App">
</div>
);
}
getAvailablePropertyTypes
is a function. It doesn't have a propertyTypes
property, so you are going to get undefined
for that.
undefined
is not a URL to anything useful, so you get an error page when you make a network request to it. The error page is not JSON, hence the error message.
There's no URL anywhere near this code. It doesn't make sense to involve fetch
at all.
fetch
is useful for getting data from APIs that are implemented as web services. It won't help you with other kinds of APIs, including this one which is just some functions dealing with internal data.
So let's go back to the start and look at what you do have.
getAvailablePropertyTypes
is a function. So call it.
const ret_value = getAvailablePropertyTypes();
It is async
so it returns a promise, so await it.
const data = await ret_value;
The resolved value of the promise is an object which does have a propertyTypes
value. So extract that.
const { propertyTypes } = data;
Now that is an array which you can do whatever you like with
console.log(propertyTypes);
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.