Home > OS >  cannot read properties of undefined on props
cannot read properties of undefined on props

Time:06-30

const Page: FC<PageProps> = () => {
  const dispatch = useAppDispatch();

  const querystring = window.location.search;
  const urlparameter = new URLSearchParams(querystring);
  const postid = Number(urlparameter.get("id"));

  const [COM] = GET_COMMENT(4); //retrieve Comments with axios
  const [data, loading, error] = RETRIEVE_POST("qna", 4); //retrieve Post Detail with axios

  useEffect(() => {
    dispatch(changeCurrentPage({ type: "/page/:uri", data: data }));
    return () => {
      dispatch(changeCurrentPage({ type: "/", data: {} }));
    };
  }, []);

  return (
    <>
      <div>
        {/* error */}
        <PostContent data={data} />
      </div>
    </>
  );
};

export default Page;
const PostContent: FC<ContentProps> = ({ data }) => {
  const { user, content } = data;
  return (
    <div>
      <div>
        {/* Post Content */}
        {content}
      </div>   
      <div>
        {/* Post Writer */}   
        <Link to={user.profileImageUrl}>
          <Writer
            imgUrl={user.profileImageUrl}
            userName={user.nickname}
          />
        </Link>
      </div>
    </div>
  );
};

I want to send data from Page to PostContent. But in ContentProps(PostContent) an error occur. Post Writer Part has trouble.

user information is undefined and all page is break.

How can I send data to child props without error?

CodePudding user response:

Check if data arrived first since you are passing undefined to the child. That is why it crashes.

    {data?.user? 
        <PostContent data={data} />
    : <p>No data here</p>}
  • Related