fetch API

PHOTO EMBED

Wed Oct 06 2021 06:32:28 GMT+0000 (UTC)

Saved by @chillymood #html

 useEffect(() => {
    fetch("https://jsonplaceholder.typicode.com/todos")
      .then(function (response) {
        return response.json();
      })
      .then(function (myJson) {
        console.log(myJson);
      	
      	//改變state
        setTodoItemData([...myJson]);
      });
  }, []);

//async 寫法

 const [isLoading, setIsLoading] = useState(false);
  const [isError, setIsError] = useState(false);
  const [todos, setTodos] = useState([]);
useEffect(() => {
    (async function () {
      try {
        const res = await fetch("https://jsonplaceholder.typicode.com/todos");
        const data = await res.json();
        setTodos(data);
        setIsLoading(false);
      } catch (err) {
        setIsLoading(false);
        setIsError(true);
      }
    })();
  }, []);

//post寫法+ 改變header

let user = {
  name: 'John',
  surname: 'Smith'
};

let response = await fetch('https://jsonplaceholder.typicode.com/posts', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json;charset=utf-8'
  },
  body: JSON.stringify(user)
});

let result = await response.json();
alert(result.id);
content_copyCOPY