{"id":7019,"date":"2021-10-30T14:50:16","date_gmt":"2021-10-30T14:50:16","guid":{"rendered":"https:\/\/programmingfields.com\/?p=7019"},"modified":"2026-05-02T06:29:32","modified_gmt":"2026-05-02T06:29:32","slug":"api-request-handling-in-react-functional-component-using-react-hook","status":"publish","type":"post","link":"https:\/\/programmingfields.com\/api-request-handling-in-react-functional-component-using-react-hook\/","title":{"rendered":"API Handling in React Functional Component Using Hook"},"content":{"rendered":"\n<p>In React, we have already seen the API request handling in a class component. The class component is the old approach in React JS. After releasing <strong>React 16.8<\/strong>,&nbsp;we are accustomed to the functional component. The functional component helps in writing a more cleaned-up code than the class component. In React posts, I have already shared tutorials on <a rel=\"noreferrer noopener\" href=\"https:\/\/programmingfields.com\/crud-app-in-react-js-using-laravel-7-restful-api\/\" target=\"_blank\" data-type=\"URL\" data-id=\"https:\/\/programmingfields.com\/crud-app-in-react-js-using-laravel-7-restful-api\/\">CRUD<\/a> and <a rel=\"noreferrer noopener\" href=\"https:\/\/programmingfields.com\/create-a-todo-app-in-react-using-laravel-8-restful-apis\/\" target=\"_blank\">Todo App<\/a> using the class component. Also, in our last post on React, we have seen the use of React hook. Now, it&#8217;s time to group the functional component and <strong>react hook <\/strong>to handle the API request. For API request handling, we will use the Axios library. To manage the state, we will use the <strong>React useState hook<\/strong>. Also, instead of life cycle methods, we will use the useEffect hook.<\/p>\n\n\n\n<div id=\"ez-toc-container\" class=\"ez-toc-v2_0_82_2 counter-hierarchy ez-toc-counter ez-toc-light-blue ez-toc-container-direction\">\n<div class=\"ez-toc-title-container\">\n<p class=\"ez-toc-title\" style=\"cursor:inherit\">Table of Contents<\/p>\n<span class=\"ez-toc-title-toggle\"><a href=\"#\" class=\"ez-toc-pull-right ez-toc-btn ez-toc-btn-xs ez-toc-btn-default ez-toc-toggle\" aria-label=\"Toggle Table of Content\"><span class=\"ez-toc-js-icon-con\"><span class=\"\"><span class=\"eztoc-hide\" style=\"display:none;\">Toggle<\/span><span class=\"ez-toc-icon-toggle-span\"><svg style=\"fill: #999;color:#999\" xmlns=\"http:\/\/www.w3.org\/2000\/svg\" class=\"list-377408\" width=\"20px\" height=\"20px\" viewBox=\"0 0 24 24\" fill=\"none\"><path d=\"M6 6H4v2h2V6zm14 0H8v2h12V6zM4 11h2v2H4v-2zm16 0H8v2h12v-2zM4 16h2v2H4v-2zm16 0H8v2h12v-2z\" fill=\"currentColor\"><\/path><\/svg><svg style=\"fill: #999;color:#999\" class=\"arrow-unsorted-368013\" xmlns=\"http:\/\/www.w3.org\/2000\/svg\" width=\"10px\" height=\"10px\" viewBox=\"0 0 24 24\" version=\"1.2\" baseProfile=\"tiny\"><path d=\"M18.2 9.3l-6.2-6.3-6.2 6.3c-.2.2-.3.4-.3.7s.1.5.3.7c.2.2.4.3.7.3h11c.3 0 .5-.1.7-.3.2-.2.3-.5.3-.7s-.1-.5-.3-.7zM5.8 14.7l6.2 6.3 6.2-6.3c.2-.2.3-.5.3-.7s-.1-.5-.3-.7c-.2-.2-.4-.3-.7-.3h-11c-.3 0-.5.1-.7.3-.2.2-.3.5-.3.7s.1.5.3.7z\"\/><\/svg><\/span><\/span><\/span><\/a><\/span><\/div>\n<nav><ul class='ez-toc-list ez-toc-list-level-1 ' ><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-1\" href=\"https:\/\/programmingfields.com\/api-request-handling-in-react-functional-component-using-react-hook\/#Prerequisites\" >Prerequisites<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-2\" href=\"https:\/\/programmingfields.com\/api-request-handling-in-react-functional-component-using-react-hook\/#Create_React_App_For_API_Handling_Using_React_Hook\" >Create React App For API Handling Using React Hook<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-3\" href=\"https:\/\/programmingfields.com\/api-request-handling-in-react-functional-component-using-react-hook\/#Install_Axios_in_React_For_API_Handling\" >Install Axios in React For API Handling<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-4\" href=\"https:\/\/programmingfields.com\/api-request-handling-in-react-functional-component-using-react-hook\/#Install_Bootstrap_in_React\" >Install Bootstrap in React<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-5\" href=\"https:\/\/programmingfields.com\/api-request-handling-in-react-functional-component-using-react-hook\/#Install_React_Router_DOM\" >Install React Router DOM<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-6\" href=\"https:\/\/programmingfields.com\/api-request-handling-in-react-functional-component-using-react-hook\/#Create_Components_in_React_JS\" >Create Components in React JS<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-7\" href=\"https:\/\/programmingfields.com\/api-request-handling-in-react-functional-component-using-react-hook\/#Export_Components_From_a_Landing_Component\" >Export Components From a Landing Component<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-8\" href=\"https:\/\/programmingfields.com\/api-request-handling-in-react-functional-component-using-react-hook\/#Posts_Listing_Using_React_Hook\" >Posts Listing Using React Hook<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-9\" href=\"https:\/\/programmingfields.com\/api-request-handling-in-react-functional-component-using-react-hook\/#Create_Post_With_React_Hook\" >Create Post With React Hook<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-10\" href=\"https:\/\/programmingfields.com\/api-request-handling-in-react-functional-component-using-react-hook\/#View_Post\" >View Post<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-11\" href=\"https:\/\/programmingfields.com\/api-request-handling-in-react-functional-component-using-react-hook\/#Edit_Post\" >Edit Post<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-12\" href=\"https:\/\/programmingfields.com\/api-request-handling-in-react-functional-component-using-react-hook\/#Delete_Post\" >Delete Post<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-13\" href=\"https:\/\/programmingfields.com\/api-request-handling-in-react-functional-component-using-react-hook\/#Final_Words\" >Final Words<\/a><\/li><\/ul><\/nav><\/div>\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Prerequisites\"><\/span><strong>Prerequisites<\/strong><span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>I am assuming you are familiar with the basic concepts of React as mentioned below-<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>React Basics<\/strong><\/li>\n\n\n\n<li><strong>Class and function component in React<\/strong><\/li>\n\n\n\n<li><strong>State in class component<\/strong><\/li>\n\n\n\n<li><strong>Life cycle methods<\/strong><\/li>\n<\/ul>\n\n\n\n<p>For the development environment, you must have the <strong>Node<\/strong> installed in your system.<\/p>\n\n\n\n<p>Before creating any app, let&#8217;s understand what we will create here. We will be handling the API request using the Axios library. Here, for the API, we will use the dummy API using the <a rel=\"noreferrer noopener\" href=\"https:\/\/jsonplaceholder.typicode.com\/\" target=\"_blank\">JSON placeholder<\/a>. In the HTTP request method, we will use the <strong>GET<\/strong>, <strong>POST<\/strong>, <strong>PUT<\/strong> and <strong>DELETE <\/strong>requests. <\/p>\n\n\n\n<p>So, let&#8217;s start by creating a new app in React. <\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Create_React_App_For_API_Handling_Using_React_Hook\"><\/span><strong>Create React App For API Handling Using React Hook<\/strong><span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>To create a new app in React, just open the terminal or command prompt and hit the below command.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code lang=\"jsx\" class=\"language-jsx\">npx create-react-app myblog<\/code><\/pre>\n\n\n\n<p>Here, the installation is started. It will take a couple of minutes to finish the installation.<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" width=\"834\" height=\"515\" src=\"https:\/\/i0.wp.com\/programmingfields.com\/wp-content\/uploads\/2021\/10\/Screenshot-from-2021-10-05-07-53-32.png?resize=834%2C515&#038;ssl=1\" alt=\"Create React App\" class=\"wp-image-7035\" srcset=\"https:\/\/i0.wp.com\/programmingfields.com\/wp-content\/uploads\/2021\/10\/Screenshot-from-2021-10-05-07-53-32.png?w=834&amp;ssl=1 834w, https:\/\/i0.wp.com\/programmingfields.com\/wp-content\/uploads\/2021\/10\/Screenshot-from-2021-10-05-07-53-32.png?resize=300%2C185&amp;ssl=1 300w, https:\/\/i0.wp.com\/programmingfields.com\/wp-content\/uploads\/2021\/10\/Screenshot-from-2021-10-05-07-53-32.png?resize=768%2C474&amp;ssl=1 768w\" sizes=\"auto, (max-width: 834px) 100vw, 834px\" \/><figcaption class=\"wp-element-caption\"><strong>Create React App<\/strong><\/figcaption><\/figure>\n<\/div>\n\n\n<p>Once the app is created, let&#8217;s navigate to the app folder. Now, run it using the below command.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code lang=\"jsx\" class=\"language-jsx\">cd myblog\nnpm start<\/code><\/pre>\n\n\n\n<p>It will redirect you to the browser automatically.<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" width=\"703\" height=\"413\" src=\"https:\/\/i0.wp.com\/programmingfields.com\/wp-content\/uploads\/2021\/06\/Screenshot-from-2021-06-18-20-31-57.png?resize=703%2C413&#038;ssl=1\" alt=\"React App Home Screen\" class=\"wp-image-6420\" srcset=\"https:\/\/i0.wp.com\/programmingfields.com\/wp-content\/uploads\/2021\/06\/Screenshot-from-2021-06-18-20-31-57.png?w=703&amp;ssl=1 703w, https:\/\/i0.wp.com\/programmingfields.com\/wp-content\/uploads\/2021\/06\/Screenshot-from-2021-06-18-20-31-57.png?resize=300%2C176&amp;ssl=1 300w\" sizes=\"auto, (max-width: 703px) 100vw, 703px\" \/><figcaption class=\"wp-element-caption\"><strong>React Homepage Running<\/strong><\/figcaption><\/figure>\n<\/div>\n\n\n<p class=\"has-text-align-center\"><a href=\"https:\/\/programmingfields.com\/how-to-create-loading-spinner-using-bootstrap-in-react-js\/\" target=\"_blank\" rel=\"noreferrer noopener\">How to Create Loading Spinner Using Bootstrap in React JS<\/a><\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Install_Axios_in_React_For_API_Handling\"><\/span><strong>Install Axios in React For API Handling<\/strong><span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>For API request handling, we will use the <strong>Axios<\/strong> library. This library will need to be installed inside the app. For installing this library, hit the below command in the terminal inside the app.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code lang=\"jsx\" class=\"language-jsx\">npm install axios<\/code><\/pre>\n\n\n\n<p>Here, the Axios library is installed in our app.<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" width=\"822\" height=\"235\" src=\"https:\/\/i0.wp.com\/programmingfields.com\/wp-content\/uploads\/2021\/10\/Screenshot-from-2021-10-05-08-00-21.png?resize=822%2C235&#038;ssl=1\" alt=\"Install Axios Library in React\" class=\"wp-image-7037\" srcset=\"https:\/\/i0.wp.com\/programmingfields.com\/wp-content\/uploads\/2021\/10\/Screenshot-from-2021-10-05-08-00-21.png?w=822&amp;ssl=1 822w, https:\/\/i0.wp.com\/programmingfields.com\/wp-content\/uploads\/2021\/10\/Screenshot-from-2021-10-05-08-00-21.png?resize=300%2C86&amp;ssl=1 300w, https:\/\/i0.wp.com\/programmingfields.com\/wp-content\/uploads\/2021\/10\/Screenshot-from-2021-10-05-08-00-21.png?resize=768%2C220&amp;ssl=1 768w\" sizes=\"auto, (max-width: 822px) 100vw, 822px\" \/><figcaption class=\"wp-element-caption\"><strong>Install Axios Library in React<\/strong><\/figcaption><\/figure>\n<\/div>\n\n\n<p>In the next step, I will be installing the Bootstrap.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Install_Bootstrap_in_React\"><\/span><strong>Install Bootstrap in React<\/strong><span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>For UI designing, we will be using Bootstrap. So, here, I am installing the latest version of Bootstrap (5.1.1).<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code lang=\"jsx\" class=\"language-jsx\">npm i bootstrap<\/code><\/pre>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" width=\"826\" height=\"235\" src=\"https:\/\/i0.wp.com\/programmingfields.com\/wp-content\/uploads\/2021\/10\/Screenshot-from-2021-10-05-08-06-31.png?resize=826%2C235&#038;ssl=1\" alt=\"Bootstrap installed in react js\" class=\"wp-image-7040\" srcset=\"https:\/\/i0.wp.com\/programmingfields.com\/wp-content\/uploads\/2021\/10\/Screenshot-from-2021-10-05-08-06-31.png?w=826&amp;ssl=1 826w, https:\/\/i0.wp.com\/programmingfields.com\/wp-content\/uploads\/2021\/10\/Screenshot-from-2021-10-05-08-06-31.png?resize=300%2C85&amp;ssl=1 300w, https:\/\/i0.wp.com\/programmingfields.com\/wp-content\/uploads\/2021\/10\/Screenshot-from-2021-10-05-08-06-31.png?resize=768%2C218&amp;ssl=1 768w\" sizes=\"auto, (max-width: 826px) 100vw, 826px\" \/><figcaption class=\"wp-element-caption\"><strong>Bootstrap Installed in React<\/strong><\/figcaption><\/figure>\n<\/div>\n\n\n<p>Now, our application is ready to create component and API handling. But, one more important functionality is still there. That is the component linking through the route. We&#8217;ll have more than one component. So, in order to interlink the components through the URL, you will need the router.<\/p>\n\n\n\n<p class=\"has-text-align-center\"><a href=\"https:\/\/programmingfields.com\/file-upload-in-react-js-using-laravel-8-restful-api\/\" target=\"_blank\" rel=\"noreferrer noopener\">File Upload in React JS Using Laravel 8 RESTful API<\/a><\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Install_React_Router_DOM\"><\/span><strong>Install React Router DOM<\/strong><span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>All the routes will be managed by this library. Hence, inside the terminal, just hit the below command.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code lang=\"jsx\" class=\"language-jsx\">npm i react-router-dom<\/code><\/pre>\n\n\n\n<p>Now, you are good to go for creating the blog app.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Create_Components_in_React_JS\"><\/span><strong>Create Components in React JS<\/strong><span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>In this post, I will show you the basic demo of API handling in React functional component. Therefore, I will create a basic blog app using the demo (fake) API for the demo purpose. However, by end of this post, you will have the brief concept of API handling using the <strong>hook in React<\/strong>.<\/p>\n\n\n\n<p>Initially, create a folder named <strong>components<\/strong> inside the <strong>src<\/strong> folder. After that create another folder inside the components folder named <strong>posts<\/strong>. Actually, it is a good practice to have a structured way of your file. Hence, your directory should look like this &#8211;<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">src\n |\n --&gt; components\n     |\n     --&gt; posts<\/pre>\n\n\n\n<p>Now, inside the posts folder, we will create the following components-<\/p>\n\n\n\n<ol class=\"wp-block-list\">\n<li><strong>CreatePost.jsx &#8211; <\/strong>This component will contain the form to create and edit post.<\/li>\n\n\n\n<li><strong>Main.jsx<\/strong> &#8211; In this component, we will list out the posts in the table format.<\/li>\n\n\n\n<li><strong>ViewPost.jsx<\/strong> &#8211; This will have the readonly fields to view the post.<\/li>\n\n\n\n<li><strong>index.js<\/strong> &#8211; All the components will be exported from this <strong>index.js<\/strong> file. This is just a landing component of all the other components.<\/li>\n\n\n\n<li><strong>MainRouter.jsx<\/strong> &#8211; We will use this component for the route management of the posts.<\/li>\n<\/ol>\n\n\n\n<p>Now, the final look after creating the components and router is like this &#8211;<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" width=\"446\" height=\"252\" src=\"https:\/\/i0.wp.com\/programmingfields.com\/wp-content\/uploads\/2021\/10\/Screenshot-from-2021-10-30-18-30-25.png?resize=446%2C252&#038;ssl=1\" alt=\"Files Structure For Posts\" class=\"wp-image-7053\" srcset=\"https:\/\/i0.wp.com\/programmingfields.com\/wp-content\/uploads\/2021\/10\/Screenshot-from-2021-10-30-18-30-25.png?w=446&amp;ssl=1 446w, https:\/\/i0.wp.com\/programmingfields.com\/wp-content\/uploads\/2021\/10\/Screenshot-from-2021-10-30-18-30-25.png?resize=300%2C170&amp;ssl=1 300w\" sizes=\"auto, (max-width: 446px) 100vw, 446px\" \/><figcaption class=\"wp-element-caption\"><strong>Files Structure For Posts<\/strong><\/figcaption><\/figure>\n<\/div>\n\n\n<p>So, the files are ready. Now, it&#8217;s time to put some code on these components. Start with <strong>index.js<\/strong>.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Export_Components_From_a_Landing_Component\"><\/span><strong>Export Components From a Landing Component<\/strong><span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>The main purpose for creating the index.js is to make a landing point of all the components inside its folder. Hence, we have the posts folder, so, add the below code.<\/p>\n\n\n\n<pre title=\"index.js\" class=\"wp-block-code\"><code lang=\"jsx\" class=\"language-jsx\">export { CreatePost } from \".\/CreatePost\";\nexport { ViewPost } from \".\/ViewPost\";\nexport { PostsMain } from \".\/Main\";\nexport { PostsRouter } from \".\/PostsRouter\";\n<\/code><\/pre>\n\n\n\n<p>However, this landing component (route) is for the posts. So, this will require to import in the <strong>App.js<\/strong>. The reason is by default, React has the main landing component as <strong>App.js<\/strong>.<\/p>\n\n\n\n<p>Therefore, let&#8217;s import it inside the App component as shown below.<\/p>\n\n\n\n<pre title=\"App.js\" class=\"wp-block-code\"><code lang=\"jsx\" class=\"language-jsx\">import React from \"react\";\nimport { PostsRouter } from \".\/components\/posts\";\nimport { BrowserRouter as Router } from \"react-router-dom\";\nimport \".\/App.css\";\n\nexport const App = () =&gt; {\n  return (\n    &lt;&gt;\n      &lt;Router&gt;\n        &lt;PostsRouter \/&gt;\n      &lt;\/Router&gt;\n    &lt;\/&gt;\n  );\n};\n\nexport default App;\n<\/code><\/pre>\n\n\n\n<p class=\"has-text-align-center\"><a href=\"https:\/\/programmingfields.com\/form-handling-in-react-js-with-validation-using-react-state\/\" target=\"_blank\" rel=\"noreferrer noopener\">Form Handling in React JS With Validation Using React State<\/a><\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Posts_Listing_Using_React_Hook\"><\/span><strong>Posts Listing Using React Hook<\/strong><span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>For the blog posts API, I will use <a rel=\"noreferrer noopener\" href=\"https:\/\/jsonplaceholder.typicode.com\" target=\"_blank\">jsonplaceholder<\/a>. You may use other sources for the fake API. Even you can create a <a rel=\"noreferrer noopener\" href=\"https:\/\/programmingfields.com\/create-rest-api-in-laravel-8-using-jwt-authentication\/\" target=\"_blank\">RESTful API<\/a> and then integrate it here.<\/p>\n\n\n\n<pre title=\"Main.jsx\" class=\"wp-block-code\"><code lang=\"jsx\" class=\"language-jsx\">import React, { useState, useEffect } from \"react\";\nimport axios from \"axios\";\nimport { useLocation, useHistory } from \"react-router-dom\";\nimport { Link } from \"react-router-dom\";\n\nexport const PostsMain = () =&gt; {\n  const [posts, setPosts] = useState([]);\n  const history = useHistory();\n\n  useEffect(() =&gt; {\n    getPosts();\n  }, []);\n\n  \/\/ get posts\n  const getPosts = () =&gt; {\n    axios\n      .get(\"https:\/\/jsonplaceholder.typicode.com\/posts\")\n      .then((response) =&gt; {\n        if (response.status === 200) {\n          setPosts(response?.data);\n        }\n      })\n      .catch((error) =&gt; {\n        console.log(error);\n      });\n  };\n\n  \/\/  action click\n  const actionClick = (data) =&gt; {\n    data.e.stopPropagation();\n\n    if (data &amp;&amp; data?.action &amp;&amp; data?.action?.type === \"view\") {\n      history.push(`\/posts\/view\/${data?.post?.id}`);\n      return false;\n    } else if (data &amp;&amp; data?.action &amp;&amp; data?.action?.type === \"edit\") {\n      history.push(`\/posts\/edit\/${data?.post?.id}`);\n      return false;\n    } else if (data &amp;&amp; data?.action &amp;&amp; data?.action?.type === \"delete\") {\n      deletePost(data?.post?.id);\n      return false;\n    }\n  };\n\n  \/\/  delete post\n  const deletePost = (postId) =&gt; {\n    axios\n      .delete(`https:\/\/jsonplaceholder.typicode.com\/posts\/${postId}`)\n      .then((response) =&gt; {\n        if (response.status === 200) {\n          console.log(response);\n        }\n      })\n      .catch((error) =&gt; {\n        console.log(error);\n      });\n  };\n\n  return (\n    &lt;div className=\"container my-4\"&gt;\n      &lt;div className=\"row\"&gt;\n        &lt;div className=\"col-xl-6\"&gt;\n          &lt;h4 className=\"fw-bold\"&gt;API Handing Using React Hooks&lt;\/h4&gt;\n        &lt;\/div&gt;\n\n        &lt;div className=\"col-xl-6 text-end\"&gt;\n          &lt;Link to={`\/posts\/create`} className=\"btn btn-sm btn-primary\"&gt;           \n            Create Post\n          &lt;\/Link&gt;\n        &lt;\/div&gt;\n      &lt;\/div&gt;\n\n      &lt;table className=\"table table-striped my-5\"&gt;\n        &lt;thead&gt;\n          &lt;tr&gt;\n            &lt;th&gt;Id&lt;\/th&gt;\n            &lt;th&gt;Title&lt;\/th&gt;\n            &lt;th&gt;Description&lt;\/th&gt;\n            &lt;th&gt;Action&lt;\/th&gt;\n          &lt;\/tr&gt;\n        &lt;\/thead&gt;\n\n        &lt;tbody&gt;\n          {posts &amp;&amp;\n            posts.map((post) =&gt; (\n              &lt;tr\n                key={post?.id}\n                onClick={(e) =&gt;\n                  actionClick({ action: { type: \"view\" }, post, e })\n                }\n              &gt;\n                &lt;td&gt; {post?.id} &lt;\/td&gt;\n                &lt;td&gt; {post?.title} &lt;\/td&gt;\n                &lt;td&gt; {post?.body} &lt;\/td&gt;\n                &lt;td&gt;\n                  &lt;Link\n                    to={\"#\"}\n                    onClick={(e) =&gt;\n                      actionClick({ action: { type: \"edit\" }, post, e })\n                    }\n                    title={\"Edit\"}\n                  &gt;\n                    Edit\n                  &lt;\/Link&gt;\n\n                  &lt;Link\n                    to={\"#\"}\n                    className=\"ms-3\"\n                    onClick={(e) =&gt;\n                      actionClick({ action: { type: \"delete\" }, post, e })\n                    }\n                    title={\"Delete\"}\n                  &gt;\n                    Delete\n                  &lt;\/Link&gt;\n                &lt;\/td&gt;\n              &lt;\/tr&gt;\n            ))}\n        &lt;\/tbody&gt;\n      &lt;\/table&gt;\n    &lt;\/div&gt;\n  );\n};\n<\/code><\/pre>\n\n\n\n<p>In the above code, I have used <a rel=\"noreferrer noopener\" href=\"https:\/\/programmingfields.com\/how-to-use-useeffect-hook-in-react-functional-component\/\" target=\"_blank\">useEffect<\/a>, and <a rel=\"noreferrer noopener\" href=\"https:\/\/programmingfields.com\/state-in-functional-component-in-react-using-usestate-hook\/\" target=\"_blank\">useState<\/a> React hook. I already shared a post on the React hook. The <strong>useEffect hook<\/strong> is used here as the component life cycle method.<\/p>\n\n\n\n<p>To check the result, open the browser with the posts route as shown below.<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-large\"><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" width=\"1024\" height=\"501\" src=\"https:\/\/i0.wp.com\/programmingfields.com\/wp-content\/uploads\/2021\/10\/Screenshot-from-2021-10-30-19-16-38.png?resize=1024%2C501&#038;ssl=1\" alt=\"Posts Rendering through Axios in React JS Using Hook\" class=\"wp-image-7060\" srcset=\"https:\/\/i0.wp.com\/programmingfields.com\/wp-content\/uploads\/2021\/10\/Screenshot-from-2021-10-30-19-16-38.png?resize=1024%2C501&amp;ssl=1 1024w, https:\/\/i0.wp.com\/programmingfields.com\/wp-content\/uploads\/2021\/10\/Screenshot-from-2021-10-30-19-16-38.png?resize=300%2C147&amp;ssl=1 300w, https:\/\/i0.wp.com\/programmingfields.com\/wp-content\/uploads\/2021\/10\/Screenshot-from-2021-10-30-19-16-38.png?resize=768%2C376&amp;ssl=1 768w, https:\/\/i0.wp.com\/programmingfields.com\/wp-content\/uploads\/2021\/10\/Screenshot-from-2021-10-30-19-16-38.png?w=1268&amp;ssl=1 1268w\" sizes=\"auto, (max-width: 1000px) 100vw, 1000px\" \/><figcaption class=\"wp-element-caption\"><strong>Posts Rendering through Axios in React JS Using Hook<\/strong><\/figcaption><\/figure>\n<\/div>\n\n\n<p>When you will click on <strong>Create Post<\/strong>, it will open the CreatePost component.<\/p>\n\n\n\n<p class=\"has-text-align-center\"><a href=\"https:\/\/programmingfields.com\/create-react-routing-in-react-js-using-react-router-dom\/\" target=\"_blank\" rel=\"noreferrer noopener\">Brief Overview of React Routing Using React Router DOM<\/a><\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Create_Post_With_React_Hook\"><\/span><strong>Create Post With React Hook<\/strong><span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>For creating the post, you will need a form with two inputs-<\/p>\n\n\n\n<ol class=\"wp-block-list\">\n<li><strong>title and<\/strong><\/li>\n\n\n\n<li><strong>body<\/strong><\/li>\n<\/ol>\n\n\n\n<p>The same component will be used for updating the post too. To manage the input control, we used React useState hook. The form inputs value is set in the state using React Hook. Hence, check the result in the browser.<\/p>\n\n\n\n<pre title=\"CreatePost.jsx\" class=\"wp-block-code\"><code lang=\"jsx\" class=\"language-jsx\">import React, { useEffect, useState } from \"react\";\nimport axios from \"axios\";\nimport { useHistory } from \"react-router-dom\";\n\nexport const CreatePost = ({ isEdit, match }) =&gt; {\n  const [post, setPost] = useState([]);\n  const history = useHistory();\n\n  useEffect(() =&gt; {\n    getPost();\n  }, [match?.params?.id]);\n\n  const formSubmit = (event) =&gt; {\n    event.preventDefault();\n\n    const createResult = !isEdit &amp;&amp; createPost();\n    createResult &amp;&amp; console.log(\"Success! post created\");\n    const updateResult = isEdit &amp;&amp; updatePost();\n    updateResult &amp;&amp; console.log(\"Success! post updated\");\n  };\n\n  \/\/   fetch post\n  const getPost = () =&gt; {\n    axios\n      .get(`https:\/\/jsonplaceholder.typicode.com\/posts\/${match?.params?.id}`)\n      .then((response) =&gt; {\n        if (response.status === 200) {\n          setPost(() =&gt; response?.data);\n        }\n      })\n      .catch((error) =&gt; {\n        console.log(error);\n      });\n  };\n\n  \/\/   create post\n  const createPost = () =&gt; {\n    axios\n      .post(\"https:\/\/jsonplaceholder.typicode.com\/posts\", {\n        title: post?.title,\n        body: post?.body,\n      })\n      .then((response) =&gt; {\n        response &amp;&amp;\n          response?.status === 200 &amp;&amp;\n          history.push(`\/posts\/view\/${match?.params?.id}`);\n      })\n      .catch((error) =&gt; {\n        console.log(error);\n      });\n  };\n\n  \/\/   update post\n  const updatePost = () =&gt; {\n    axios\n      .put(`https:\/\/jsonplaceholder.typicode.com\/posts\/${match?.params?.id}`, {\n        title: post?.title,\n        body: post?.body,\n      })\n      .then((response) =&gt; {\n        response &amp;&amp;\n          response?.status === 200 &amp;&amp;\n          history.push(`\/posts\/view\/${match?.params?.id}`);\n        console.log(response.data);\n      })\n      .catch((error) =&gt; {\n        console.log(error);\n      });\n  };\n\n  \/\/   onchange event\n  const onChange = (e) =&gt; {\n    setPost({\n      ...post,\n      [e.target.name]: e.target.value,\n    });\n  };\n\n  return (\n    &lt;div className=\"container my-4\"&gt;\n      &lt;div className=\"row\"&gt;\n        &lt;div className=\"col-xl-6 m-auto\"&gt;\n          &lt;form method={\"POST\"} onSubmit={(e) =&gt; formSubmit(e)}&gt;\n            &lt;div className=\"card\"&gt;\n              &lt;div className=\"card-header\"&gt;\n                &lt;h5 className=\"card-title\"&gt; {!isEdit &amp;&amp; 'Create Post' || 'Update Post'} &lt;\/h5&gt;\n              &lt;\/div&gt;\n\n              &lt;div className=\"card-body\"&gt;\n                &lt;div className=\"form-group\"&gt;\n                  &lt;label&gt; Title &lt;\/label&gt;\n                  &lt;input\n                    type=\"text\"\n                    className=\"form-control\"\n                    placeholder=\"Title\"\n                    name=\"title\"\n                    onChange={(e) =&gt; onChange(e)}\n                    value={post?.title}\n                  \/&gt;\n                &lt;\/div&gt;\n\n                &lt;div className=\"form-group my-3\"&gt;\n                  &lt;label&gt; Description &lt;\/label&gt;\n                  &lt;textarea\n                    className=\"form-control\"\n                    onChange={(e) =&gt; onChange(e)}\n                    placeholder=\"Description\"\n                    name=\"body\"\n                    rows=\"6\"\n                    value={post?.body}\n                  &gt;&lt;\/textarea&gt;\n                &lt;\/div&gt;\n              &lt;\/div&gt;\n\n              &lt;div className=\"card-footer\"&gt;\n                &lt;button type=\"submit\" className=\"btn btn-success\"&gt;\n                  {(isEdit &amp;&amp; \"Update\") || \"Save\"}\n                &lt;\/button&gt;\n              &lt;\/div&gt;\n            &lt;\/div&gt;\n          &lt;\/form&gt;\n        &lt;\/div&gt;\n      &lt;\/div&gt;\n    &lt;\/div&gt;\n  );\n};\n<\/code><\/pre>\n\n\n\n<p>Here, I haven&#8217;t handled the validation for this form. I already shared the post on the <a href=\"https:\/\/programmingfields.com\/form-handling-in-react-js-with-validation-using-react-state\/\" target=\"_blank\" rel=\"noreferrer noopener\">form handling with validation<\/a>.<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" width=\"690\" height=\"551\" src=\"https:\/\/i0.wp.com\/programmingfields.com\/wp-content\/uploads\/2021\/10\/Screenshot-from-2021-10-30-19-38-09.png?resize=690%2C551&#038;ssl=1\" alt=\"Create Post\" class=\"wp-image-7067\" srcset=\"https:\/\/i0.wp.com\/programmingfields.com\/wp-content\/uploads\/2021\/10\/Screenshot-from-2021-10-30-19-38-09.png?w=690&amp;ssl=1 690w, https:\/\/i0.wp.com\/programmingfields.com\/wp-content\/uploads\/2021\/10\/Screenshot-from-2021-10-30-19-38-09.png?resize=300%2C240&amp;ssl=1 300w\" sizes=\"auto, (max-width: 690px) 100vw, 690px\" \/><figcaption class=\"wp-element-caption\"><strong>Create Post<\/strong><\/figcaption><\/figure>\n<\/div>\n\n\n<p>On submit, it will call the <strong>formSubmit<\/strong> function, defined inside the above component.<\/p>\n\n\n\n<p class=\"has-text-align-center\"><a href=\"https:\/\/programmingfields.com\/create-a-todo-app-in-react-using-laravel-8-restful-apis\/\" target=\"_blank\" rel=\"noreferrer noopener\">Create a Todo App in React Using Laravel 8 RESTful APIs<\/a><\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"View_Post\"><\/span><strong>View Post<\/strong><span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>When you will click on the row of the table inside the Posts listing, it will check the action type. We already passed the action type inside the <strong>actionClick()<\/strong> function. As per the action, it will redirect to the route respectively.<\/p>\n\n\n\n<figure class=\"wp-block-image size-full\"><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" width=\"1011\" height=\"543\" src=\"https:\/\/i0.wp.com\/programmingfields.com\/wp-content\/uploads\/2021\/10\/Screenshot-from-2021-10-30-19-42-01.png?resize=1011%2C543&#038;ssl=1\" alt=\"Post View in React Using Hook\" class=\"wp-image-7068\" srcset=\"https:\/\/i0.wp.com\/programmingfields.com\/wp-content\/uploads\/2021\/10\/Screenshot-from-2021-10-30-19-42-01.png?w=1011&amp;ssl=1 1011w, https:\/\/i0.wp.com\/programmingfields.com\/wp-content\/uploads\/2021\/10\/Screenshot-from-2021-10-30-19-42-01.png?resize=300%2C161&amp;ssl=1 300w, https:\/\/i0.wp.com\/programmingfields.com\/wp-content\/uploads\/2021\/10\/Screenshot-from-2021-10-30-19-42-01.png?resize=768%2C412&amp;ssl=1 768w\" sizes=\"auto, (max-width: 1000px) 100vw, 1000px\" \/><figcaption class=\"wp-element-caption\"><strong>Post View in React Using Hook<\/strong><\/figcaption><\/figure>\n\n\n\n<p>In the <strong>ViewPost<\/strong> component,<strong> <\/strong>there are two more buttons as you can see in the above result. On clicking of <strong>Edit<\/strong> button, it will redirect to the <strong>CreatePost<\/strong> component in edit mode. Let&#8217;s check that.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Edit_Post\"><\/span><strong>Edit Post<\/strong><span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>When a post is opened in the <strong>edit<\/strong> mode, the card title inside the <strong>CreatePost<\/strong> is changed to <strong>Update Post.<\/strong> Also, the same button (<strong>Save<\/strong>) is renamed as <strong>Update<\/strong>. After updating the post, it will redirect to the View Post again.<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" width=\"696\" height=\"577\" src=\"https:\/\/i0.wp.com\/programmingfields.com\/wp-content\/uploads\/2021\/10\/Screenshot-from-2021-10-30-19-47-21.png?resize=696%2C577&#038;ssl=1\" alt=\"Edit\/Update Post\" class=\"wp-image-7070\" srcset=\"https:\/\/i0.wp.com\/programmingfields.com\/wp-content\/uploads\/2021\/10\/Screenshot-from-2021-10-30-19-47-21.png?w=696&amp;ssl=1 696w, https:\/\/i0.wp.com\/programmingfields.com\/wp-content\/uploads\/2021\/10\/Screenshot-from-2021-10-30-19-47-21.png?resize=300%2C249&amp;ssl=1 300w\" sizes=\"auto, (max-width: 696px) 100vw, 696px\" \/><figcaption class=\"wp-element-caption\"><strong>Edit\/Update Post<\/strong><\/figcaption><\/figure>\n<\/div>\n\n\n<p class=\"has-text-align-center\"><a href=\"https:\/\/programmingfields.com\/react-login-and-registration-app-using-laravel-7-api\/\" target=\"_blank\" rel=\"noreferrer noopener\">React Login and Registration App Using Laravel 7 API<\/a><\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Delete_Post\"><\/span><strong>Delete Post<\/strong><span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>The functionality of deleting the post is handled inside with the same action click function. When you will click on the delete action, it will hit the <strong>deletePost<\/strong>() function. Here, I used the fake API, hence, the post won&#8217;t be deleted and updated. It is just for demo purposes.<\/p>\n\n\n\n<p>However, you will see the success response message in the console. You can integrate <strong>snackbar<\/strong> component or an alert component for that. But, we will see that in our upcoming post when we will work with <strong>Material UI<\/strong> in React.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Final_Words\"><\/span><strong>Final Words<\/strong><span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>In this demo app, we implemented the API requests handling in React functional component. For API request handling we used the <strong>Axios<\/strong> library. The React hooks are used here to manage state, and life cycle methods. By using this way, you can implement it in your React app functional component. This was just for the demonstration purpose of API handling in the React functional component. Hence, I haven&#8217;t designed it very well and the validation, response message, delete confirmation is not there. But, we will see all these things in the separate post of the upcoming React series. I hope you will find helpful to this post.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>In React, we have already seen the API request handling in a class component. The class component is the old approach in React JS. After releasing React 16.8,&nbsp;we are accustomed to the functional component. The functional component helps in writing a more cleaned-up code than the class component. In React posts, I have already shared [&hellip;]<\/p>\n","protected":false},"author":5,"featured_media":7073,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_genesis_hide_title":false,"_genesis_hide_breadcrumbs":false,"_genesis_hide_singular_image":false,"_genesis_hide_footer_widgets":false,"_genesis_custom_body_class":"","_genesis_custom_post_class":"","_genesis_layout":"","jetpack_post_was_ever_published":false,"_jetpack_newsletter_access":"","_jetpack_dont_email_post_to_subs":false,"_jetpack_newsletter_tier_id":0,"_jetpack_memberships_contains_paywalled_content":false,"_jetpack_memberships_contains_paid_content":false,"footnotes":"","jetpack_publicize_message":"","jetpack_publicize_feature_enabled":true,"jetpack_social_post_already_shared":false,"jetpack_social_options":{"image_generator_settings":{"template":"highway","default_image_id":0,"font":"","enabled":false},"version":2}},"categories":[1369],"tags":[1594,1593,2196,2194,2132,2133,2195],"yst_prominent_words":[652,1450,823,1793,1541,1286,105,1401],"class_list":{"0":"post-7019","1":"post","2":"type-post","3":"status-publish","4":"format-standard","5":"has-post-thumbnail","7":"category-react","8":"tag-apis-in-react","9":"tag-axios-in-react","10":"tag-effect-hook-in-react-js","11":"tag-hooks-in-react-js","12":"tag-http-request-handling-in-react","13":"tag-react-axios-api-handling","14":"tag-state-hook-in-react-js","15":"entry"},"jetpack_publicize_connections":[],"jetpack_featured_media_url":"https:\/\/i0.wp.com\/programmingfields.com\/wp-content\/uploads\/2021\/10\/API-handling-using-Hook.png?fit=2240%2C1260&ssl=1","jetpack_likes_enabled":true,"jetpack_sharing_enabled":true,"jetpack-related-posts":[],"_links":{"self":[{"href":"https:\/\/programmingfields.com\/wp-json\/wp\/v2\/posts\/7019","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/programmingfields.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/programmingfields.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/programmingfields.com\/wp-json\/wp\/v2\/users\/5"}],"replies":[{"embeddable":true,"href":"https:\/\/programmingfields.com\/wp-json\/wp\/v2\/comments?post=7019"}],"version-history":[{"count":2,"href":"https:\/\/programmingfields.com\/wp-json\/wp\/v2\/posts\/7019\/revisions"}],"predecessor-version":[{"id":8933,"href":"https:\/\/programmingfields.com\/wp-json\/wp\/v2\/posts\/7019\/revisions\/8933"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/programmingfields.com\/wp-json\/wp\/v2\/media\/7073"}],"wp:attachment":[{"href":"https:\/\/programmingfields.com\/wp-json\/wp\/v2\/media?parent=7019"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/programmingfields.com\/wp-json\/wp\/v2\/categories?post=7019"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/programmingfields.com\/wp-json\/wp\/v2\/tags?post=7019"},{"taxonomy":"yst_prominent_words","embeddable":true,"href":"https:\/\/programmingfields.com\/wp-json\/wp\/v2\/yst_prominent_words?post=7019"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}