Reputation: 35
I have this error « Error: TypeError: Cannot destructure property 'id' of 'fetchedData' as it is undefined. » and I don’t know how to deal with it
It’s a react app (port 3001) that use a micro API (port 3000).
import Data from "./Data";
export default class Service {
/**
* Fetch the user main data from the API
* @param {function} resolve the function for success
* @param {number} id the user ID
* @return {void}
*/
getData = (resolve, id) => {
fetch(`http://localhost:3000/user/${id}`)
.then((response) => response.json())
.then((result) => {
const data = new Data();
console.log(result)
resolve(data.getData(result.data));
})
.catch((error) => {
console.log("Error: ", error);
})
};
}
the console log tell me « can not get user »
here is the Data class
export default class Data {
/**
* Service to handle the fetched data (user data)
* @param {object} fetchedData The data from the API
* @return {object} The formatted data for the front
*/
getData(fetchedData) {
const { id, userInfos } = fetchedData;
const { firstName, lastName, age } = userInfos;
const userObj = new Infos(firstName, lastName, age);
const userDataObj = new MainData(id, userObj);
return userDataObj;
}
}
I’ve no idea how to deal with this error and where is my mistake.
Upvotes: 1
Views: 2142
Reputation: 35
So I finally found a solution, the problem was to be able to retrieve the id inside the url and use it in the different child components that needed it. It's not a very elegant solution but it worked.
/**
* Fetch the user main data from the API
* @param {number} id the user ID
* @param {function} resolve the function for success
* @param {function} reject the fonction to handle error
* @return {void}
*/
getData = (id) => {
return new Promise((resolve, reject) => {
fetch(`http://localhost:3000/user/${id}`)
.then((response) => response.json())
.then((result) => {
const data = new Data();
resolve(data.getData(result.data));
})
.catch((error) => {
reject(error);
})
})
};
And how I use it in a child component
class Dashboard extends Component {
constructor(props) {
super(props);
const url = window.location.href.split("/");
this.state = {
id: url[url.length -1],
keyData: {},
};
this.service = new Service();
this.updateData = this.updateData.bind(this);
}
componentDidMount() {
this.service.getData(
this.state.id
).then(data=>{
this.updateData(data)
}).catch(error=>{
console.log(error)
})
}
Upvotes: 1