(해결중)빈 form을 입력했을 때의 예외처리

piper ·2024년 2월 16일
0

React

목록 보기
11/22

form의 상태를 배열로 넘겨주는 형태를 만들고 있기때문에
form의 값이 빈 값일 때 "데이터가 없습니다"라고 만들어주고 있다.

하지만
Cannot read properties of undefined (reading '0')
TypeError: Cannot read properties of undefined (reading '0')

위와 같은 에러를 발생시키며 작동되지 않고있다.

import React from "react";
import styled from "styled-components";
import { useState } from "react";
import AddTask from "./addTask";
import { Link } from "react-router-dom";
import Todo from "./todo";

const ToDoList = () => {
  const [list, setList] = useState([
    {
      title: "Reading a tech article",
      date: "Feb 8th 2024",
      file: [
        "https://images.pexels.com/photos/8520627/pexels-photo-8520627.jpeg?auto=compress&cs=tinysrgb&w=600",
      ],
      category: "Reading",
      todo: "Reading about the react 2024 articles ",
    },
  ]);

  const [error, setError] = useState(null);

  const onAddItem = (item) => {
    if (Object.values(item).some((value) => value === "")) {
      setError("Please fill in all input-fields.");
      return;
    }

    setError(null);
    const newItem = { ...item, id: 10 };
    setList((list) => [newItem, ...list]);
  };

  return (
    <>
      <AddTask onAdd={onAddItem} />

      <CardLayer id="myTodoSection">
        <h2>MY TODO</h2>
        <hr />
        <CardList>
          <EachCard>
            {list ? (
              list.map((l) => {
                return (
                  <div key={l.title}>
                    <TaskCard>
                      <StyledLink to={`/todo/${l.title}`}>
                        <div>
                          <h3>{l.title}</h3>
                        </div>
                        <div>
                          <p>{l.date}</p>
                        </div>
                        <div>
                          <img
                            id="img"
                            src={l.file[0]}
                            alt="imgFile"
                            style={{ width: "150px", height: "150px" }}
                          />
                        </div>
                        <div>
                          <p>{l.category}</p>
                        </div>
                        <div>
                          <p>{l.todo}</p>
                        </div>
                        <p>Read More</p>
                      </StyledLink>
                    </TaskCard>
                  </div>
                );
              })
            ) : (
              <p>{error}</p>
            )}
            <AddButton>
              <h2
                onClick={() => {
                  window.scrollTo({
                    top: 550,
                    behavior: "smooth",
                  });
                }}
              >
                add
              </h2>
            </AddButton>
          </EachCard>
        </CardList>
      </CardLayer>
      <Todo list={list} />
    </>
  );
};

export default ToDoList;
profile
연습일지

0개의 댓글