React Nx Tutorial - Step 4: Connect to an API

Real-world applications do not live in isolation — they need APIs to talk to. Setup your app to talk to an API.

Let's change our application to fetch the data from the API.

1import React, { useEffect, useState } from 'react';
2
3interface Todo {
4  title: string;
5}
6
7const App = () => {
8  const [todos, setTodos] = useState<Todo[]>([]);
9
10  useEffect(() => {
11    fetch('/api/todos')
12      .then((_) => _.json())
13      .then(setTodos);
14  }, []);
15
16  function addTodo() {
17    fetch('/api/addTodo', {
18      method: 'POST',
19      body: '',
20    })
21      .then((_) => _.json())
22      .then((newTodo) => {
23        setTodos([...todos, newTodo]);
24      });
25  }
26
27  return (
28    <>
29      <h1>Todos</h1>
30      <ul>
31        {todos.map((t) => (
32          <li className={'todo'}>{t.title}</li>
33        ))}
34      </ul>
35      <button id={'add-todo'} onClick={addTodo}>
36        Add Todo
37      </button>
38    </>
39  );
40};
41
42export default App;