React Udemy #7: Data Persistence with API Requests๐Ÿ˜ˆ

JEUNGBIN HANยท2022๋…„ 12์›” 14์ผ

React-Udemy-Lecture

๋ชฉ๋ก ๋ณด๊ธฐ
3/12
post-thumbnail

Adding Data Persistence

BAD WAY

App Component
books : [{id : 1}]
=> User Refresh Page
=>
books: []

Thsy will lose their value

GOOD WAY

The list of books is no longer going to be reset and totally releted.

Creating a data inside the database

Request

Introducing the Rest Client

VSCode
view => Extentions => rest client

Make File

# Create 
GET http://localhost:3001/books HTTP/1.1
Content-Type : application/json

Server Setup

  1. npm i json-server
  2. create 'db.json'
  3. 'package.json' =>
 "scripts": {
    "start": "react-scripts start",
    "server": "json-server -p 3001 --watch db.json",
  1. npm run server => starts JSON-Server

json-server -p 3001 --watch db.json
-p 3001 => the port the server listens to
--watch db.json => Tell the server to store data in the 'db.json'

Creating a new Record


=> npm i axios

Inside App.js

  const createBook = async (title) => {

    const response = await axios.post("http://localhost:3001/books", {
      title,
    });

    const updatedBooks = [...books, response.data];
    setBooks(updatedBooks);
  };

Fetching a list of Record

  const fetchBooks = async () => {
    const response = await axios.get("http://localhost:3001/books");
    setBooks(response.data);
  };

  useEffect(() => {
    fetchBooks();
  }, []);
profile
Web Developer

0๊ฐœ์˜ ๋Œ“๊ธ€