Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React hook with fetch api

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>
  );
}

Codesandbox

like image 936
Kaherdin Avatar asked Mar 18 '26 18:03

Kaherdin


1 Answers

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

here's and example

like image 114
k.s. Avatar answered Mar 20 '26 09:03

k.s.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!