I am getting the user data from an api using the fetch() function. In the render function I want to pass the props using the ...userdata but it gives me error when I create object before return statement. The error is : TypeError: Cannot read property 'id' of undefined
Error is because at the time of loading the application there is no userData, its fetched only on search button click.
Please let me know how can I create the object and pass it as prop, instead of passing each member of object separately as prop. i.e.
import React from 'react';
import './App.css';
import SearchBar from "./components/search";
import Result from "./components/result";
class ContactSearch extends React.Component {
constructor() {
super();
this.state = {
// userData: {
// id: 0,
// name: "",
// username: ""
// },
userData : [],
userAddr : {},
searchDone: false,
errorMessage: ""
};
this.callUserData = this.callUserData.bind(this);
}
callUserData(user) {
const url = `<URL>`;
fetch(url)
.then(handleErrors)
.then(resp => resp.json())
.then(data => {
var { ...addr} = data[0].address;
this.setState({
userData: [...data],
userAddr: addr,
searchDone: true,
errorMessage: ""
});
})
.catch(error => {
// If an error is catch, it's sent to SearchBar as props
this.setState({ errorMessage: error.message });
});
function handleErrors(response) {
if (!response.ok) {
throw Error(response.statusText);
}
return response;
}
}
render() {
const { searchDone, userData, userAddr, errorMessage } = this.state;
console.log('Inside render');
let **user** = {
id : userData[0].id,
name:userData[0].name,
email:userData[0].email,
address:userAddr
};
return (
<div className="ContactSearch">
<SearchBar
callBackFromParent={this.callUserData}
error={errorMessage}
/>
{searchDone && userData && (
<Result
{...**user**}
/>
)}
</div>
);
}
}
export default ContactSearch;