Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
583 views
in Technique[技术] by (71.8m points)

reactjs - React Typescript Object is possibly 'undefined'. TS2532

I am trying to figure out why I have this error when I am mapping on a array of objects for a simple todo project. I'm very new at Typescript and I don"t know why this happen why my state "list" is well logged in the console as an array. Can you check what's wrong?

  const ToDoListItem = () => {
  const [list, setList] = useState();

  useEffect(() => {
    fetch("http://localhost:1337/lists", {
      method: "GET",
      headers: {
        "Content-Type": "application/json",
      },
    })
      .then((response) => response.json())
      .then((data) => setList(data));
  }, []);

  const findData = async () => {
    fetch("http://localhost:1337/lists", {
      method: "GET",
      headers: {
        "Content-Type": "application/json",
      },
    })
      .then((response) => response.json())
      .then((data) => setList(data));
  };
  console.log(list);
  return (
    <Container>
      <Row>
        {list.map((e, i) => { //where the issue is coming from
          console.log(todo);
          return (
            <Col xs="12" style={{ display: "flex", justifyContent: "center" }}>
              <div className="todo-container">
                <InputGroup
                  style={{
                    display: "flex",
                    alignItems: "center",
                    width: "100%",
                    justifyContent: "space-evenly",
                  }}
                >
                  <Input
                    className="input-text"
                    value={e.todo}
                    placeholder="to do"
                  />

                  <Input
                    type="checkbox"
                    checked={e.iscompleted}
                    className="check-box"
                  />
question from:https://stackoverflow.com/questions/65905730/react-typescript-object-is-possibly-undefined-ts2532

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You need to add a type for your useState list value, for example and based in your code:

interface ListItem {
 todo: string
 isCompleted: boolean
}

const ToDoListItem = () => {
 // Set the initial value to an empty array
 const [list, setList] = useState<ListItem[]>([]);
// Rest of your code
{list.map((e, i) => {
 // More code
}}
}

With this you are typing your state, so it would allow to make typescript to infer the object values Notice that the <ListItem[]> before the useState is telling you that the value should be an array of a ListItem interface.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...