Skip to content
Advertisement

React Hooks TypeError: todos is undefined

I am using PERN Stack with bootstrap for styling. So, I want to access my JSON data and show it in the form of todo lists. When I tried using map function I got TypeError: enter image description here

Here is the code:

import React, { useState, useEffect } from "react";

const ListToDo = () => {
  const [todos, setTodos] = useState([]);

  const getTodos = async () => {
    try {
      const res = await fetch("http://localhost:3000/todos");
      const jsonData = await res.json();
      console.log(jsonData.data.todos);
      setTodos(jsonData.data.todos);
    } catch (err) {
      console.log("ERROR: ", err);
    }
  };

  useEffect(() => {
    getTodos();
  }, []);

  return (
    <>
      <ul className="list-group my-4 ">
        {todos.map((todo) => (
          <li className="list-group-item d-flex justify-content-between align-items-center">
            {todo.description}
            <span className="">
              <button className="btn btn-dark ">Edit</button>
              <span> </span>
              <button className="btn btn-dark ">Delete</button>
            </span>
          </li>
        ))}
      </ul>
    </>
  );
};

export default ListToDo;

Advertisement

Answer

I misspelled my variable. So, the problem was I was writing jsonData.data.todos instead off jsonData.data.toDos .

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement