Render Data in React

Hôm nay mình tiếp tục chia sẻ tiếp. Trong bài viết này ta sẽ thực hiện việc lấy dữ liệu từ một đường dẫn API nào đó trả về, sau đó lưu dữ liệu trả về từ API vào State.
Sau khi có dữ liệu trong State, ta render dữ liệu đó ra ngoài cho người dùng xem. Ok giờ ta tạo một project mới, thực hiện thôi. Các bạn có thể xem lại các bài viết trước tại đây:

Install Create React App & Bootstrap CSS framework

npx create-react-app render-data-react
cd render-data-react
npm install bootstrap@4.1.2

Ok, giờ ta mở file index.js trong thư mục src. Thêm file css của bootstrap như sau:

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import * as serviceWorker from './serviceWorker';
import 'bootstrap/dist/css/bootstrap.css';
ReactDOM.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>,
  document.getElementById('root')
);

// If you want your app to work offline and load faster, you can change
// unregister() to register() below. Note this comes with some pitfalls.
// Learn more about service workers: https://bit.ly/CRA-PWA
serviceWorker.unregister();

Tiếp theo mình sẽ dùng Axios để xử lý API

npm install axios

Sau khi cài đặt xong, tạo đường dẫn thư mục src/api. Sau đó tạo file index.js trong thư mục src/api
+ src/api/index.js

import axios from 'axios';
let API_URL = 'https://5adc8779b80f490014fb883a.mockapi.io';
   export default function callApi(endpoint, method = 'GET', body) {
       return axios({
           method,
           url: `${API_URL}/${endpoint}`,
           data: body
       }).catch(err => {
           console.log(err);
       });
   }

Giờ đây ta cần gọi API để trả về dữ liệu, sao đó render ra cho người dùng xem 
Tạo đường dẫn thư mục src/components/home. Rồi tạo file component Home.js trong thư mục src/components/home

import React, { Component } from 'react'
import callApi from '../../api'
class Home extends Component {
    constructor(props){
        super(props)
        this.state = {
            loading:false,
            _products:[]
        }
    }
    componentDidMount(){
        //CALL API https://5adc8779b80f490014fb883a.mockapi.io/products 
        callApi("/products",'GET',null).then(res => {
            this.setState({
                loading:true,
                _products:res.data
            })
        });
    }
    render() {
        const {loading,_products} = this.state;
        if(!loading){
            return (
                <div>
                    <h4>Loading...</h4>
                </div>
            )
        }
        return (
            <div>
                <h1>List Product</h1>
                <ul style={{display:'flex',flexWrap:'wrap'}}>
                    {
                        _products.map((item,index)=>(
                            <li key={index} style={{
                                width:'calc(100% / 4 - 20px)',
                                heigth:'80px',
                                listStyle:'none',
                                paddingRight:'20px',
                                boxSizing:'border-box',
                                margin:'10px',
                                border:'1px solid #ccc'
                            }}>
                                <h5>{item.name}</h5>
                                <strong>price : {item.price}</strong>
                            </li>
                        ))
                    }
                </ul>
            </div>
        )
    }
}

export default Home

Để dùng được file api, ta cần import api/index.js vào Home.js

import callApi from '../../api'


Thay đổi giá trị dữ liệu, khi gọi hàm callApi(), setState lại _products & loading

callApi("/products",'GET',null).then(res => {
            this.setState({
                loading:true,
                _products:res.data
            })
});

Sau khi dữ liệu đã tồn tại, ta dùng map để render dữ liệu cho người dùng

 _products.map((item,index)=>())

Ok, giờ ta cần import file component Home.js đến App.js, hãy mở file App.js lên chỉnh sửa lại như sau:

import React from 'react';
import './App.css';
import Home from './components/home/Home';

function App() {
  return (
    <div className="App">
      <Home />
    </div>
  );
}

export default App;

Vậy là xong, giờ ta start lại ứng dụng: npm start

Render Data in React

Bài Viết Liên Quan

Messsage

Ủng hộ tôi bằng cách click vào quảng cáo. Để tôi có kinh phí tiếp tục phát triển Website!(Support me by clicking on the ad. Let me have the money to continue developing the Website!)