Fetching data with hooks

杀马特。学长 韩版系。学妹 提交于 2021-02-05 07:51:30

问题


I'm having a hard time to wrap my head around the best way to fetch data from an API only once (and when it's first requested) and then storing the result for reuse and/or other component functions. Below is a working example with useContext and useReducer, but it's quite complex for such an "easy" task.

Is there a better approach? And what's the best way to implement this for a large amount of API calls. Any suggestions are greatly appreciated.

import React from "react";
import ReactDOM from "react-dom";
import axios from 'axios';

const initialState = {
  items: [],
  itemsLoading: false
};

const actions = {
  FETCHING_ITEMS: "FETCHING_ITEMS",
  FETCHED_ITEMS: "FETCHED_ITEMS"
};

const reducer = (state, action) => {
  switch (action.type) {
    case actions.FETCHING_ITEMS:
      return { ...state, itemsLoading: true, items: {} };

    case actions.FETCHED_ITEMS:
      return { ...state, items: action.value };
    default:
      return state;
  }
};

const Context = React.createContext();

const Provider = ({ children }) => {
  const [state, dispatch] = React.useReducer(reducer, initialState);

  const value = {
    items: state.items,
    itemsLoading: state.itemsLoading,
    fetchItems: () => {
      if (!state.itemsLoading) {
        dispatch({ type: actions.FETCHING_ITEMS });
        axios
          .get("https://jsonplaceholder.typicode.com/todos")
          .then(function(response) {
            dispatch({ type: actions.FETCHED_ITEMS, value: response.data });
          });
      }
    }
  };

  return <Context.Provider value={value}>{children}</Context.Provider>;
};

const Filters = () => {
  const { items, fetchItems } = React.useContext(Context);

  React.useEffect(() => {
    fetchItems();
  }, [fetchItems]);

  const listItems = items.length
    ? items.map(item => {
        return <li key={item.id}>{item.title}</li>;
      })
    : "";

  return (
    <div>
      <ul>{listItems}</ul>
    </div>
  );
};

const App = () => {
  return (
    <Provider>
      <Filters />
    </Provider>
  );
};

const rootElement = document.getElementById("root");

ReactDOM.render(
    <App />,
  rootElement
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.19.2/axios.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root"></div>

Can't get the snippet to work on SO, here is a working sandbox: https://codesandbox.io/s/falling-frog-4pdm1

Thank you!


回答1:


I imagine you could write some abstraction around this using custom hooks -

const identity = x => x

const useAsync = (runAsync = identity, deps = []) => {
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState(null)
  const [result, setResult] = useState(null)

  useEffect(_ => {
    Promise.resolve(runAsync(...deps))
      .then(setResult, setError)
      .finally(_ => setLoading(false))
  }, deps)

  return { loading, error, result }
}

You're excited so you start using it right away -

const MyComponent = () => {
  const { loading, error, result:items } =
    useAsync(_ => {
      axios.get("path/to/json")
        .then(res => res.json())
    }, ...)

  // ...
}

But stop there. Write more useful hooks when you need them -

const fetchJson = (url) =>
  axios.get(url).then(r => r.json())

const useJson = (url) =>
  useAsync(fetchJson, [url])

const MyComponent = () => {
  const { loading, error, result:items } =
    useJson("path/to/json")

  if (loading)
    return <p>Loading...</p>

  if (error)
    return <p>Error: {error.message}</p>

  return <div><Items items={items} /></div>
}

Conveniently useEffect will only re-run the effect when the dependencies change. However if you expect to have expensive queries that you wish to handle with finer control, look at useCallback and useMemo.



来源:https://stackoverflow.com/questions/61778948/fetching-data-with-hooks

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!