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);
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter