Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Hooks - Making an Ajax request

Tags:

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>     ) } 
like image 352
peter flanagan Avatar asked Oct 30 '18 07:10

peter flanagan


People also ask

How do you make AJAX call in React hooks?

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.

Which functions did we use in React to initiate an AJAX request?

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 a React component should you make an AJAX?

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.


1 Answers

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>     ); } 
like image 158
Paul Fitzgerald Avatar answered Oct 18 '22 13:10

Paul Fitzgerald