首页 > 解决方案 > React Hooks - 使用帖子中的新数据刷新页面上的一些数据

问题描述

我有一个仅在安装时才获取数据的组件。理想情况下,我只想进行一次此调用,因为它正在获取大量数据。当我发出发布请求时,我会收到想要在页面上显示的新数据并乐观地更新 UI。我不想再次重新获取数据,因为这是一个昂贵的调用,而是只想更新更改的数据。我可以创建一个 API 端点,我调用它来获取有关更新的必要数据,但为什么不使用从发布请求中收到的数据来更新数据呢?

示例代码:

const App = () => {
  const [error, setError] = useState(false);
  const [loading, setLoading] = useState(false);
  const [alert, setAlert] = useState(null);
  // data states
  const [user, setUser] = useState(null);
  const [account, setAccount] = useState(null);
  const [key, setKey] = useState(null);
  const [externalAccount, setExternalAccount] = useState(null);
  const [showModal, setShowModal] = useState(false);

  // fetch data upon component mount
  useEffect(() => {
    const fetchData = async () => {
      setLoading(true);
      try {
        // Get data for working with accounts
        const res = await get(
          '/api/v1/account'
        );

        setUser(res.data.user);
        setAccount(res.data.account);
        setKey(res.data.key);
        setExternalAccount(res.data.external_account);
      } catch (e) {
        setError(e);
      }

      setLoading(false);
    };

    fetchData();
  }, []);

  const createAccount = async params => {
    setLoading(true);
    try {
      // send request
      const res = await post(
        '/api/v1/account',
        params
      );

      // set updated account data
      setAccount(res.data.account); //doesn't update on the page. I could call a refetch in the above useEffect but not ideal. Any other options?

      // set success alert
      setAlert('Your account was created successfully.');

      // update loading state
      setLoading(false);
    } catch (e) {
      setAlert(e.message);
      setLoading(false);
    }
  };


  // Define page renders
  if (error) return <ErrorComponent />;
  if (loading) return <Loader />;

  return (
    <>
      <h1>Account</h1>
      {account &&
        <div>
          //display information using state information on user and account
        </div>
      }
      {showModal &&
         <CreateModal 
           toggleModal={setShowModal} 
           createAccount={createAccount} 
           user={user} 
           account={account}
         />
       }
    </>
  );
}

const CreateModal = ({ toggleModal, createAccount }) => {
  const handleSubmit = e => {
    e.preventDetault();
    const params = // set up params for post request
    
    createAccount(params)

  return (
    <form onSubmit={e => handleSubmit(e)}>
      //form code here
    </form>
  )
}

标签: reactjsreact-hooksfetch-api

解决方案


推荐阅读