Hello i trying to build webpart with sharepoint and react. But i am unable to build simple api fetch.
export default class Testing100 extends React.Component<ITesting100Props, {}> {
constructor(props: ITesting100Props) {
super(props);
this.state = { fetchedData: [] };
}
componentDidMount() {
fetch(`https://api.randomuser.me/`)
.then((res) => res.json())
.then((fetchedData) => this.setState({ fetchedData }));
}
public render(): React.ReactElement<ITesting100Props> {
return (
<p>{this.state.fetchedData.results.name.first}</p> {/*fetchedData is red with error Property 'fetchedData' does not exist on type 'Readonly<{}>'. */}
);
}
}
API output looks like this
{"results":[{"gender":"female","name":{"title":"Miss","first":"Justine","last":"Macdonald"},"location":{"street":{"number":3332,"name":"St. Lawrence Ave"},"city":"Wellington","state":"Yukon","country":"Canada","postcode":"O1T 4H9","coordinates":{"latitude":"-63.5927","longitude":"62.6969"},"timezone":{"offset":"+6:00","description":"Almaty, Dhaka, Colombo"}},"email":"justine.macdonald@example.com","login":{"uuid":"a90c5dff-dcf6-4c6b-bb82-22e3ed2f930c","username":"blackcat228","password":"longdong","salt":"W7AVyRES","md5":"7ab07000c4c9f6ddb85d296e417f33a6","sha1":"abefc0e0cd002308f9dcad4ce4d91645d0d27231","sha256":"604e2318a0bc7af3df622acdb15f316b42090d1d4eb23b102e415519d52dedd1"},"dob":{"date":"1993-10-31T21:03:14.503Z","age":27},"registered":{"date":"2006-04-17T22:55:50.380Z","age":14},"phone":"819-520-7512","cell":"844-873-6971","id":{"name":"","value":null},"picture":{"large":"https://randomuser.me/api/portraits/women/88.jpg","medium":"https://randomuser.me/api/portraits/med/women/88.jpg","thumbnail":"https://randomuser.me/api/portraits/thumb/women/88.jpg"},"nat":"CA"}],"info":{"seed":"723b7f94b557aa40","results":1,"page":1,"version":"1.3"}}
What i want to do is just to print firstname but i am unable to do it i will be thankfull for any help.
this.state.fetchedData.results[0].name.first
`. The results property is an _array_ and you need to first access the element you must include an index - in this case - 0 – Slavian Jul 23 '20 at 15:48