0

my code is below:

const [todos, setTodos] = useState('');

I am using a fake server.

function getTodos () {
  axios.get('http://localhost:4000/todos')
  .then(function (response) {
    setTodos(response.data);
  })
  .catch(function (error) {
    console.log(error);
  })
  .then(function () {
  });
}

<tbody id="tableBody">
        {
          todos.map((item) => (
            <tr key={item.id}>
                <td>{item.id}</td>
                <td>{item.task}</td>
                <td>{item.desc}</td>
                <td>{item.due}</td>
                <td>{item.status}</td>
            </tr>
          ))
        }
        </tbody>

But I am getting this error: TypeError: todos.map is not a function

1
  • 6
    You're most likely getting this error because thanks to const [todos, setTodos] = useState(''); when the component renders first, todos is a string. Use const [todos, setTodos] = useState([]); instead. Commented Jun 16, 2021 at 10:13

2 Answers 2

1

First, you should use empty array default value for your todos

const [todos, setTodos] = useState([]);

Than check what you setting in todos setTodos(response.data);

Probably error is because of default value of todos

Sign up to request clarification or add additional context in comments.

Comments

0

As your todos is an array [todos, setTodos] = useState('') is wrong and you need to set it to an empty array const [todos, setTodos] = useState([]); And also whenever you get simillar error keep in mind that there is some problem with todos array it isnt an array or you are handling it in a wrong way

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.