<aside> 💡 정말 미친듯이 날 괴롭혔던 위의 에러에 대해 정리해보자

</aside>

원인(나의 원인은 2번)

1. render를 하거나 props로 내려줄 때, 자료형식에 맞지 않게 내려주는 경우

2. ❗️setState에서 return 값으로 새로운 object를 통채로 return할때

//정상 작동 코드
...
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 ;  =>  지금 주제인 해당 오류발생
          }
        });

Try

🥲1. 하나의 새로운 객체를 만들어 리턴하기 ⇒ (return temp)

temp라는 객체를 만들어 해당 객체 자체를 return temp 해보았으나, Objects are not valid as a React child 라는 에러 문구를 만났다.

🥲2. 구조분해 문법을 사용하여 리턴 ⇒ (return { temp })

당연히 구조분해 문법이 되어, state = {temp : {sth: [incomingM]}} 형식으로 들어가게 되었고, 이는 내가 원하는 state구조가 아니라 실패했다.

🥲3. spread로 풀어서 리턴 ⇒ (return { ...temp })

이건 된다! 라고 생각했지만, 다시한번! Objects are not valid as a React child 라는 에러 문구를 만났다.

⭐️4. default값에 미리 키값을 넣어주고, 해당 키값만 바꿔주어 리턴

⇒ (return { data: temp })