React Using APIs: Difference between revisions

From bibbleWiki
Jump to navigation Jump to search
Line 27: Line 27:
})
})


</syntaxhighlight>
So within React this would look like this
<syntaxhighlight lang="js">
const [events, setEvents] = useState([])
useEffect(() => {
    fetch("/path/to/API")
    .then(response => response.json())
    .then(data => {
        setEvents(data)
    })
}, [])
</syntaxhighlight>
</syntaxhighlight>

Revision as of 06:22, 23 June 2021

Introduction

This page is for how to use APIs with React.

When to call APIs

When using API here is where you should call the APIs

API for calling APIs

Options

There were 4 options offered.

  • Fetch API (Newish but OK)
  • Axios (Believe it is popular and have used)
  • JQuery (Never used)
  • XMLHttpRequest (old and liked - no surprise there)

Using Fetch

Here are the to ways to use fetch.

fetch("/path/to/API")
    .then(response => response.json())
    .then(data => {/* */})

const response = await fetch("/path/to/API");
const data = await response.json();

fetch("/path/to/API", {
    method: "POST",
    body: JSON.stringify(data),
    headers: { 'Content-Type': 'application/json'}
})

So within React this would look like this

const [events, setEvents] = useState([])

useEffect(() => {
    fetch("/path/to/API")
    .then(response => response.json())
    .then(data => {
        setEvents(data)
    })
}, [])