React useReducer async data fetch

前端 未结 6 673
臣服心动
臣服心动 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:19

    Update:

    I’ve added another comment in the weblink below. It’s a custom hook called useAsyncReducer based on the code below that uses the exact same signature as a normal useReducer.

    function useAsyncReducer(reducer, initState) {
        const [state, setState] = useState(initState),
            dispatchState = async (action) => setState(await reducer(state, action));
        return [state, dispatchState];
    }
    
    async function reducer(state, action) {
        switch (action.type) {
            case 'switch1':
                // Do async code here
                return 'newState';
        }
    }
    
    function App() {
        const [state, dispatchState] = useAsyncReducer(reducer, 'initState');
        return ;
    }
    
    function ExampleComponent({ dispatchState }) {
        return ;
    }
    

    Old solution:

    I just posted this reply here and thought it may be good to post here as well in case it helps anyone.

    My solution was to emulate useReducer using useState + an async function:

    async function updateFunction(action) {
        switch (action.type) {
            case 'switch1':
                // Do async code here (access current state with 'action.state')
                action.setState('newState');
                break;
        }
    }
    
    function App() {
        const [state, setState] = useState(),
            callUpdateFunction = (vars) => updateFunction({ ...vars, state, setState });
    
        return ;
    }
    
    function ExampleComponent({ callUpdateFunction }) {
        return 

提交回复
热议问题