nx/docs/react/tutorial/04-connect-to-api.md
2021-01-14 15:31:44 -05:00

1.4 KiB
Raw Blame History

Step 4: Connect to an API

Video of this Lesson

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.

import React, { 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;

!!!!! Run npx nx serve todos and open http://localhost:4200. What do you see? !!!!! "the server responded with a status of 404 (Not Found)" in Console. Blank screen. Exception rendered on the screen.