redux - fetch internet data and put to component asynchronously

Commit

Install libraies
npm install --save redux react-redux axios redux-thunk

define get data api (jsonPlarceholder is a tool site for testing)
src/apis/jsonPlaceholder.js
import axios from 'axios';

export default axios.create({
    baseURL: 'https://jsonplaceholder.typicode.com'
});

enable redux thunk for applying async operation
src/index.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import {createStore, applyMiddleware} from 'redux'
import { Provider } from 'react-redux'
import reducers from './reducers'
import thunk from "redux-thunk";

const store = createStore(reducers, applyMiddleware(thunk));

ReactDOM.render(
      <Provider store={store} >
          <App />
      </Provider>,
  document.getElementById('root')
);

dispatch fetch data result in action creator
Reference if you feel "() => async dispatch =>" seems weird:  https://www.isaacnote.com/2020/06/redux-shorten-async-function.html
src/actions/index.js
export const fetchPosts = () => async dispatch => {
    console.log("action fetchPosts")
    const response = await jsonPlaceholder.get('/posts')

    dispatch({type:'FETCH_POSTS', payload: response})
}

define reducer to set up fetch result to state
src/reducers/index.js
export const fetchPostReducer = (fetchPosts = null, action) => {
    console.log("fetchPostReducer", fetchPosts, action)
    if (action.type === 'FETCH_POSTS') {
        console.log("return action", action.payload.data)
        return action.payload.data;
    }

    return fetchPosts
}

fetch data when mount component
src/components/PttPosts.js
import React, {Component} from "react";
import {connect} from 'react-redux'
import {fetchPosts, selectPttPost} from "../actions";

class PttPosts extends Component {
    componentDidMount() {
        console.log('fetch posts')
        this.props.fetchPosts()
    }

    renderList() {
        if (this.props.postList) {
            console.log("renderList", this.props.postList)
            return this.props.postList.map((post) => {
                console.log("map", post)
                return <div key={post.id}>
                    <div key={post.id}><a onClick={() => this.props.selectPttPost(post)}>Title:{post.title}</a></div>
                </div>
            });
        } else {
            return 'Loading...'
        }
    };

    render() {
        console.log('render', this.props)
        return <div>{this.renderList()}</div>
    }
}

const mapStateToProps = (state) => {
    console.log("mapStateToProps",state)
    return {postList: state.fetchPosts};
}

export default connect(mapStateToProps, { fetchPosts, selectPttPost })(PttPosts)

npm start and check result, can click item to show article





沒有留言:

張貼留言

別名演算法 Alias Method

 題目 每個伺服器支援不同的 TPM (transaction per minute) 當 request 來的時候, 系統需要馬上根據 TPM 的能力隨機找到一個適合的 server. 雖然稱為 "隨機", 但還是需要有 TPM 作為權重. 解法 別名演算法...