CRUD #1 Get Data From API in React.Js

Posted at: February 25, 2019 4:36 PM

How to fetch data from API in React

In this lesson you can learn how to fetch or get data from api in React and also learn how to use api in React with the help of an example. API has created in CodeIgniter and MySQL.

Bootstrap also installed in this tutorial. You can learn how to Integrate Bootstrap with React Js

Create src/ProductList.js file and create stateful component ProductList and import Table from react-bootstrap

import { Table } from 'react-bootstrap';

We use componentDidMount(), It is React Lifecycle Method. When you will use API, then we want to use componentDidMount() Lifecycle Method. Component has rendered to the DOM before bringing the data from API. So call api in componentDidMount() method.

src/ProductList.js

Please see complete code of src/ProductList.js

src/App.js

Import ProductList component from ./ProductList for showing the proudct list and Container from react-bootstrap for design.

src/index.js

API

API has created in CodeIgniter. You can learn CodeIgniter 3 Tutorial Step By Step

Controller

application/controllers/ReactApi.php

Model

application/models/ReactApi_model.php

MySQL Database `products` Table

Conclusion

In this lesson we have learned, how to get or fetch data from api in React with the help of an example of the product list. We have covered JavaScript method fetch() for getting data from api, and use componentDidMount() for component has rendered before bringing data from api.

This lesson also available on YouTube
API ComponentDidMount Fetch CodeIgniter MySQL

Please leave comments

8 Comments