Home > Software design >  App.js:32 Uncaught TypeError: Tasks.map is not a function
App.js:32 Uncaught TypeError: Tasks.map is not a function

Time:12-26

I really don't know what's actually wrong with the code(below)

import Todo from './components/task.js'
import axios from 'axios'

import { useState } from 'react';
import { useEffect } from 'react';

function App() {
const [Tasks, setTasks] = useState([]);


  useEffect(() => {

    async function fetchTasks() {
      await axios.get('http://localhost:5000/task')
      .then(({data})=> setTasks(data))
      .catch((err)=>console.log(err))
      
    }
    fetchTasks();
  }, []);

  if (Error){
    <p>{Error.message}</p>
  }

  return (
    <div className="App">
      <div className="container-container">
        <h1>AppTodo</h1>
        <div className="input-class">
          <input type="text" placeholder="Add your todos" id="input1-id" />
          <input type="submit" id="input2-id" value="Add" />
        </div>
        {Tasks.map((items) => <Todo key={items._id} text={items.name} />)}
      </div>
    </div>
  );
}

export default App;

I tried changing to fetch api method and yet still can't get anything also tried to console.log the Tasks hence I have setTask in the useEffect() it seems the it fail to set it inside the task. I am just expecting the output of the list of the items.

CodePudding user response:

Add Optional chaining operator with the Task array like below

{Tasks?.map((items) => )}

CodePudding user response:

You just need to reomve {} curly brackets from data in .then 

useEffect(() => {

    async function fetchTasks() {
      await axios.get('http://localhost:5000/task')
      .then((data)=> setTasks(data))
      .catch((err)=>console.log(err))
      
    }
    fetchTasks();
  }, []);
  
  I have removed your curly brackets from line 5. 

  • Related