Reputation: 2127
I want to make a very simple Fetch request (or axios request) and then map these results.
For that, I'm using useState and useEffect, but I'm definitively doing something wrong.
function App() {
const [todos, setTodos] = useState({});
const getTodos = () => {
const urlTodos = "https://jsonplaceholder.typicode.com/todos/";
return fetch(urlTodos)
.then(res => res.json())
.then(res => {
return res
});
};
useEffect(() => {
getTodos().then(setTodos);
}, []);
const [todosSimple, setTodosSimple] = ([
{
text: 'learn about react',
isCompleted :true
},
{
text: 'Danse',
isCompleted: false
}
])
console.log(todosSimple)
return (
<div className="App">
{todosSimple.map((todo,index) => {
return todo;
}
)}
</div>
);
}
Upvotes: 3
Views: 1140
Reputation: 3004
Well first of all you need to change this line
const [todos, setTodos] = useState({});
to
const [todos, setTodos] = useState([]);
Since todos
variable is going to have a default value, and it's going to be an empty object. And there is no .map
method on objects, and well you receive an array from the api.
Secondly I would recommend using setTodos
function inside the getTodos
in the last then.
.then(res => setTodos(res))
and then you can map your todos
in the return
Upvotes: 2