jh.nrtv

Fetch ์‚ฌ์šฉ๋ฒ•(get, post, put, delete) , ์ปค์Šคํ…€ ํ›… useFetch ๋ณธ๋ฌธ

Network, server

Fetch ์‚ฌ์šฉ๋ฒ•(get, post, put, delete) , ์ปค์Šคํ…€ ํ›… useFetch

wlgus3 2023. 1. 26. 16:39

โœ… Fetch ์‚ฌ์šฉ๋ฒ• 

 

๐Ÿ”ธ GET (๋ฐ์ดํ„ฐ ๊ฐ€์ ธ์˜ค๊ธฐ /  ์กด์žฌํ•˜๋Š” ์ž์›์„ ์š”์ฒญ)

fetch('url')
  .then((response)=>(response.json()))
  .then((data)=>console.log(data))

response๋Š” ๊ฐ์ฒดํ˜•ํƒœ

 

 

๐Ÿ”ธ POST (๋ฐ์ดํ„ฐ ์ƒ์„ฑํ•˜๊ธฐ /  ์ƒˆ๋กœ์šด ์ž์› ์ƒ์„ฑ ์š”์ฒญ)

fetch("http://localhost:3001/blogs", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify({
        id: blogs.length + 1,
        title: title,
        body: body,
        author: author,
        likes: 0,
      }),
    })
  .then((response) => response.json())
  .then((data) => console.log(data));

 

๐Ÿ”ธ PUT ( ์กด์žฌํ•˜๋Š” ์ž์› ๋ณ€๊ฒฝ ์š”์ฒญ ) 

fetch(`http://localhost:3001/blogs/${id}`, {
        method: "PUT",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({
          ...data,
          likes: data.likes - 1,
        }),
      })
        .then((response) => response.json())
        .then((data) => console.log(data));
      console.log("Reject like!");

 

๐Ÿ”ธ DELETE (๋ฐ์ดํ„ฐ ์‚ญ์ œํ•˜๊ธฐ / ์กด์žฌํ•˜๋Š” ์ž์› ์‚ญ์ œ ์š”์ฒญ)

๊ธฐ๋ณธํ˜•ํƒœ

fetch(`http://localhost:3001/blogs/${id}`, {
      method: "DELETE", //! delete๋Š” body ํ•„์š”์—†์ด ๋ฉ”์„œ๋“œ๋งŒ ์ „๋‹ฌํ•ด์ฃผ๋ฉด ๋จ
    })
      .then((response) => response.json())
      .then((data) => console.log(data));
	.catch(error=>console.log(error));

 


โœ…  ์ปค์Šคํ…€ ํ›… - useFetch(url)

import { useState, useEffect } from "react";

const useFetch = (url) => {
  // const [data,setData] = useState(null)
  const [data, setData] = useState(null);
  const [isPending, setIsPending] = useState(true);
  const [error, setError] = useState(null);

  useEffect(() => {
    setTimeout(() => {
      fetch(url)
        .then((res) => {
          if (!res.ok) {
            throw Error("could not fetch the data for that resource");
          }
          return res.json();
        })
        .then((data) => {
          setIsPending(false);
          setData(data);
          setError(null);
        })
        .catch((err) => {
          setIsPending(false);
          setError(err.message);
        });
    }, 1000);
  }, [url]);

  return [data, isPending, error]; /* return ๋ฌธ์„ ์ž‘์„ฑํ•ด์ฃผ์„ธ์š”. */
};

export default useFetch;

 

 

'Network, server' ์นดํ…Œ๊ณ ๋ฆฌ์˜ ๋‹ค๋ฅธ ๊ธ€

[Deploy] AWS ์‹ค์Šต  (0) 2023.02.02
[Deploy] AWS  (2) 2023.02.02