I was trying to destructure my ProfileData variable that holds an object. But, I have a problem to display the API data, so when it passes, my page breaks and sends me this error "Cannot destructure property 'picture' of 'profileData' as it is undefined.".I don't know the reason of the error message is the absence of the key "last_paper" in some objects but I don't know how to avoid this problem. I don't know where the problem is and I don't know how to avoid this problem.
function Profile() {
const { id: queryId } = useParams();
const [profileData, setProfileData] = useState({});
useEffect(() => {
fetch(`http://localhost:8000/freelance?id=${queryId}`)
.then((response) => response.json())
.then((jsonResponse) => {
setProfileData(jsonResponse?.freelaneData);
});
}, [queryId]);
const { picture, name, location, tjm, job, skills, available, id } = profileData;
CodePudding user response:
If you don't want your site to crash when profileData is undefined . Just follow the below code :
function Profile() {
const { id: queryId } = useParams();
const [profileData, setProfileData] = useState({});
useEffect(() => {
fetch(`http://localhost:8000/freelance?id=${queryId}`)
.then((response) => response.json())
.then((jsonResponse) => {
setProfileData(jsonResponse?.freelaneData);
});
}, [queryId]);
const { picture, name, location, tjm, job, skills, available, id } = profileData || {};
In this case , picture , name or other properties which we are trying to de structure will be undefined .
CodePudding user response:
It looks like freelaneData
is not present in all responses.
Either normalise your database response to include an empty object anyhow, or fallback to an empty object like:
setProfileData(jsonResponse?.freelaneData || {});
CodePudding user response:
I just fixed the problem I had misspelled freelaneData instead of freelanceData. Thank you for your help.
function Profile() {
const { id: queryId } = useParams();
const [profileData, setProfileData] = useState({});
useEffect(() => {
fetch(`http://localhost:8000/freelance?id=${queryId}`)
.then((response) => response.json())
.then((jsonResponse) => {
setProfileData(jsonResponse?.freelanceData);
});
}, [queryId]);
const { picture, name, location, tjm, job, skills, available, id } =
profileData;