codestates / codestates/HomeTownAlba

[21.11.11] 에러핸들링 (김지윤) - setTimeout 내에서 setState를 사용해도 useEffect가 작동 안 됨

Open
#99 0 comments 0 reactions 0 assignees View on GitHub
Dominant language
JavaScript
Stars
0
Forks
0
PR merge metrics
No merged PRs in 30d

Description

## 문제 상황 및 에러 로그
- 상황 : setTimeout 내에서 setState를 실행해서 state를 변경해도, useEffect 가 작동 안 됨
```js
const [eventStatus, setEventStatus] = useState(false);

const createCareer = () => {
axios
.post(
`${process.env.REACT_APP_SERVER_URL}/career`,
{
jobSeekerId,
company,
period,
position: careerPosition,
},
{ withCredentials: true }
)
.then((res) => {
setEventStatus(!eventStatus) // setTimeout 외부 setState 사용

setTimeout(()=>{
axios.delete(`${process.env.REACT_APP_SERVER_URL}/career/${res.data.id}`, {withCredentials: true})
.then((res)=>{
setEventStatus(!eventStatus) // setTimeout 내부 setState 사용
})
}, 300000)
})
.catch((err) => {
console.log(err);
});
};

useEffect(() => {
// 함수 코드
}, [eventStatus])
```

## 원인 및 해결방안
- 원인
- setState를 setTimeout 밖에서 이미 사용함
- 따라서 setTimeout 내부의 setState는 state를 변경시키지 못함 (이미 위에서 변경되었기 때문)
- state가 변경되지 않으므로, useEffect가 작동되지 않음

- 해결방안 : 다른 Hook를 선언하고, 이를 setTimeout 내에서 사용하기
```js
const [eventStatus, setEventStatus] = useState(false);
const [eventSetTimeout, setEventSetTimeout] = useState(false); // 추가로 state 선언

const createCareer = () => {
axios
.post(
`${process.env.REACT_APP_SERVER_URL}/career`,
{
jobSeekerId,
company,
period,
position: careerPosition,
},
{ withCredentials: true }
)
.then((res) => {
setEventStatus(!eventStatus)

setTimeout(()=>{
axios.delete(`${process.env.REACT_APP_SERVER_URL}/career/${res.data.id}`, {withCredentials: true})
.then((res)=>{
setEventSetTimeout(!eventSetTimeout); // 추가로 선언된 setState 사용
})
}, 300000)
})
.catch((err) => {
console.log(err);
});
};

useEffect(() => {
// 함수 코드
}, [eventStatus, eventSetTimeout]) // 종속성 배열에 새로 선언된 state를 엘리먼트로 추가
```

Contributor guide

No contributing guide indexed for this repository

Research direction

Search the frontend for createCareer, the eventStatus state, and the useEffect that depends on it. Reproduce the delayed axios.delete flow and inspect whether the state change inside setTimeout triggers the effect; done means the delayed update is observed by useEffect without breaking the existing create flow.

Written by the indexing model from the issue text.

Assessment

Tech stack
javascript
Domain
frontend
Issue type
Bug
Difficulty
2/5
Estimated time
1-3 hours
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.