Async, Await를 사용했지만 동기처럼 보여지게 해주는 비동기처리식일뿐 실제로 동기는 아니다. 그래서 서버에서 데이터를 받아오기 전에 랜더링이 되었다. 랜더링이 될때 서버에서 정보를 받아오지 않았기에 오류가 생겼다. 이 부분을 Axios Loading을 만들어 해결 할 수 있다.
function Dosurvey() {
const [surveyDetail, setSurveyDetail] = useState(null) //axios를 통해 받아오는 설문 상세 정보 state
const [loading, setLoading] = useState(false) // axios에서 정보를 받아오고 랜더링하기 위한 상태 state
const [error, setError] = useState(null) // 에러발생시 에러를 저장할 수 있는 state
useEffect(() => {
setLoading(true)
const jwt = localStorage.getItem('jwt')
axios.get(`/survey/${params.surveyId}`, {
headers: {
Authorization: 'Bearer ' + jwt
}
})
.then((res) => {
setLoading(false)
setSurveyDetail(res.data.result)
})
.catch((Error) => {
setError(Error)
})
}, [])
if (loading) return (
<div>로딩중...</div>
)
if (error) return (
<div>에러 발생..{error}</div>
)
if (!surveyDetail) return (
null
)
return(
<>test</>
)
}