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.
fetchedData?result.datais undefined when you pass it intogetData(), and it's failing atconst { id, userInfos } = fetchedDatabecause fetchedData is now undefined.${id}inside backticks is not at all related to the destructuring{ id } = whatever, so I'm confused about your last comment.