SyntaxError: Unexpected token u in JSON at position 0 에러 해결법

최석훈·2022년 5월 30일
0

문제

상황은 이와 같았다. API로 받아온 데이터가 string이었는데 JSON.stringify로 변환되어있던 데이터라서 JSON.parse로 다시 JSON으로 변환하려고 했다.

const [name, setName] = useState();

useEffect(async ()=>{
	try{
    	const profile = await getProfileData();
    	setData(JSON.parse(profile.car));
    }catch{
    	console.log("error");
    }
},[]);


근데 이와같은 에러가 발생하였다.
JSON.parse에서 에러가 난 모양이다.

해결

문제가 발행한 이유는 porofile가 비어있을 수 있는데 빈 데이터를 parse하려고 해서 에러가 난 것이다. 그래서 나는 이렇게 해결을 하였다.

 const [name, setName] = useState();

useEffect(async ()=>{
	try{
    	const profile = await getProfileData();
    	setData(profile ? JSON.parse(profile.car) : '');
    }catch{
    	console.log("error");
    }
},[]);

이렇게 비었을 경우를 처리해주면 된다.

profile
하루를 열심히

0개의 댓글