React useReducer async data fetch

前端 未结 6 680
臣服心动
臣服心动 2020-11-30 22:36

I\'am trying to fetch some data with new react useReducer API and stuck on stage where i need to fetch it async. I just don\'t know how :/

How to place data fetching

6条回答
  •  囚心锁ツ
    2020-11-30 23:13

    You can use the useAsync package: https://github.com/sonofjavascript/use-async, which basically is an extension of the useReducer hook that allows managing asynchronous actions over application's state through http requests.

    Set the client agent (you can use your own http client) through the ClientStore:

    import React from 'react'
    
    import { ClientStore } from '@sonofjs/use-async'
    import axios from 'axios'
    
    import Component from './Component.jsx'
    
    const ViewContainer = () => (
      
        
      
    )
    
    export default ViewContainer
    

    Define and use your actions:

    import React, { useEffect }  from 'react'
    import useAsync from '@sonofjs/use-async'
    
    const actions = {
      FETCH_DATA: (state) => ({
        ...state,
        loading: true,
        request: {
          method: 'GET',
          url: '/api/data'
        }
      }),
      FETCH_DATA_SUCCESS: (state, response) => ({
        ...state,
        loading: false,
        data: response
      }),
      FETCH_DATA_ERROR: (state, error) => ({
        ...state,
        loading: false,
        error
      })
    }
    
    const initialState = {
      loading: false,
      data: {}
    }
    
    const Component = () => {
      const [state, dispatch] = useAsync(actions, initialState)
    
      useEffect(() => {
        dispatch({ type: 'DATA' })
      }, [])
    
      return (
        <>
          {state.loading ? Loading... : null}
          {{JSON.stringify(state.data)}}
          {state.error ? Error: {JSON.stringify(state.error)} : null}
        <>
      )
    }
    
    export default Component
    

提交回复
热议问题