I have just began playing around with React hooks and am wondering how an AJAX request should look?
I have tried many attempts, but am unable to get it to work, and also don't really know the best way to implement it. Below is my latest attempt:
import React, { useState, useEffect } from 'react'; const App = () => { const URL = 'http://api.com'; const [data, setData] = useState({}); useEffect(() => { const resp = fetch(URL).then(res => { console.log(res) }); }); return ( <div> // display content here </div> ) }
create a new React Hook. this Hook will accept an URL to fetch and a series of options (queries, method and body) this Hook will return an object with the AJAX response and a loading and error boolean values. Every time one of the options given to the hook is changed, the Hook will fetch again the URL.
In this method, we initiate the AJAX request using XMLHttpRequest . We use the GET method and https://programming-quotes-api.herokuapp.com/quotes/page/1 as the endpoint which returns a JSON output of first page quotes. readystatechange handler is called when the readyState of the request changes.
Where in the component lifecycle should I make an AJAX call? You should populate data with AJAX calls in the componentDidMount lifecycle method. This is so you can use setState to update your component when the data is retrieved.
You could create a custom hook called useFetch
that will implement the useEffect
hook.
By passing an empty array as the second argument to the useEffect
hook will trigger the request on componentDidMount
.
Here is a demo in code sandbox.
See code below.
import React, { useState, useEffect } from 'react'; const useFetch = (url) => { const [data, setData] = useState(null); // empty array as second argument equivalent to componentDidMount useEffect(() => { async function fetchData() { const response = await fetch(url); const json = await response.json(); setData(json); } fetchData(); }, [url]); return data; }; const App = () => { const URL = 'http://www.example.json'; const result = useFetch(URL); return ( <div> {JSON.stringify(result)} </div> ); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With