<aside> 💡 정말 미친듯이 날 괴롭혔던 위의 에러에 대해 정리해보자
</aside>
//정상 작동 코드
...
const [msg, setMsg] = useState({ data: {} });
setMsg((prev) => {
const temp = { ...prev.data };
const sender = from;
if (!temp[to]) {
temp[sender] = [incomingM];
if (!temp[to]) {
temp[to] = [incomingM];
} else {
temp[to].push(incomingM);
}
return { data: temp };
} else {
if (!temp[to]) {
temp[to] = [incomingM];
} else {
temp[to].push(incomingM);
}
temp[sender].push(incomingM);
return { data: temp };
}
});
//오류발생 코드
...
const [msg, setMsg] = useState({});
setMsg((prev) => {
const temp = { ...prev};
const sender = from;
if (!temp[to]) {
temp[sender] = [incomingM];
if (!temp[to]) {
temp[to] = [incomingM];
} else {
temp[to].push(incomingM);
}
return { data: temp };
} else {
if (!temp[to]) {
temp[to] = [incomingM];
} else {
temp[to].push(incomingM);
}
temp[sender].push(incomingM);
return { temp }; => 당연히 state가 이제 {temp : {sth: [incomingM]}} 형식으로 들어가게 된다.
return temp ; => 지금 주제인 해당 오류발생
}
});
temp라는 객체를 만들어 해당 객체 자체를 return temp 해보았으나, Objects are not valid as a React child 라는 에러 문구를 만났다.
당연히 구조분해 문법이 되어, state = {temp : {sth: [incomingM]}} 형식으로 들어가게 되었고, 이는 내가 원하는 state구조가 아니라 실패했다.
이건 된다! 라고 생각했지만, 다시한번! Objects are not valid as a React child 라는 에러 문구를 만났다.
⇒ (return { data: temp })