nx/docs/shared/react-tutorial/04-connect-to-api.md
Isaac Mann a49ac56789
docs(react): update react tutorial (#8757)
* docs(react): update react tutorial

* docs(core): update nx dev

Co-authored-by: Isaac Mann <isaacplmann+git@gmail.com>
2022-01-28 20:57:53 +00:00

53 lines
1.2 KiB
Markdown
Raw Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# React Nx Tutorial - Step 4: Connect to an API
<iframe loading="lazy" width="560" height="315" src="https://www.youtube.com/embed/HexxYHpIfAo" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture; fullscreen"></iframe>
Real-world applications do not live in isolationthey 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.**
```typescript
import { useEffect, useState } from 'react';
interface Todo {
title: string;
}
const App = () => {
const [todos, setTodos] = useState<Todo[]>([]);
useEffect(() => {
fetch('/api/todos')
.then((_) => _.json())
.then(setTodos);
}, []);
function addTodo() {
fetch('/api/addTodo', {
method: 'POST',
body: '',
})
.then((_) => _.json())
.then((newTodo) => {
setTodos([...todos, newTodo]);
});
}
return (
<>
<h1>Todos</h1>
<ul>
{todos.map((t) => (
<li className={'todo'}>{t.title}</li>
))}
</ul>
<button id={'add-todo'} onClick={addTodo}>
Add Todo
</button>
</>
);
};
export default App;
```