Note: This site is currently "Under construction". I'm migrating to a new version of my site building software. Lots of things are in a state of disrepair as a result (for example, footnote links aren't working). It's all part of the process of building in public. Most things should still be readable though.

Fetching Data From An API With a Button onClick Event Handler In React

TODO: Combine these two posts into one (or eliminate one if they are duplicates)

/fetching-data-from-an-api-with-a-button-onclick-event-handler-in-react-2 /fetching-data-from-an-api-with-a-button-onclick-event-handler-in-react

This is how I'm fetching data from a remote API via a button's onClick event handler in React.

Code

<!DOCTYPE HTML>
<html>
<head>
    <title>Fetching Remote Data With A Button Click And Error Handling</title>  
    <script src="https://unpkg.com/react@16.12.0/umd/react.development.js"></script>
    <script src="https://unpkg.com/react-dom@16.12.0/umd/react-dom.development.js"></script>
    <script src="https://unpkg.com/@babel/standalone@7.8.3/babel.js"></script>
<style>
body { background-color: #555; }
</style>

</head>
<body>
    <p>Fetching Remote Data With A Button Click</p>
    <p><a href="/">Home</a></p>
    <div id="root"></div>
    <script type="text/babel">
        function App() {
            const [statusMessage, setStatusMessage] = React.useState('TBD')
            const [isFetching, setIsFetching] = React.useState(false)

            React.useEffect(() => {
                if (isFetching) {
                    window.fetch('https://api.weather.gov/')
                        .then(response => response.json())
                        .then(
                            response => {
                                setStatusMessage(response.status)
                            },
                            errorData => {
                                setStatusMessage('ERROR')
                            }
                        )
                    setIsFetching(false)
                }
            })

            return (
                <div>
                    <div>API Status: {statusMessage}</div>
                    <button onClick={() => setFetchStatus('pending')}>Check Status</button>
                </div>
            )
        }

        ReactDOM.render(<App/>, document.getElementById('root'))
    </script>
</body>
</html>

Notes:

- This example uses `unpkg.com` to call versions of react and babel to make it stand alone, but the script will function in a regular React app. - In a regular app, you'd use `