admin管理员组

文章数量:1123273

I have recently started a new react project using Vite, and I updated it from React 18.3 (which Vite came with) to React 19 (on react, react-dom and their type modules), as I wish to use the new use() hook as it seems very helpful for reducing code for http requests.

However, when I try run my code, it gets stuck in the Suspense component and starts repeatedly making http requests.

import { Suspense, use } from 'react';
import axios from 'axios';

function App() {
  return (
  <>
    <h1>Hello World!</h1>

    <Suspense fallback={<p>loading</p>}>
      <SteamApiGameCountRequest />
    </Suspense>
  </>);
}

function SteamApiGameCountRequest() {

  const response = use(getGames());

  return (<p>I have {response.response.game_count} games</p>);
}

async function getGames() {
  const res = await axios.get('http://localhost:5173/GetOwnedGames', 
    { 
      params: {
        format: 'json',
        steamid: '76561198194449583'
  }});
  
  return res.data;
}

export default App;

html page stuck in the Suspense fallback component while repeatedly making http requests

I know the issue is unrelated to any of my async code as I have gotten it to work successfully using the useEffect() hook.

import { useEffect, useState } from 'react';
import axios from 'axios';

function App() {
  return (
  <>
    <h1>Hello World!</h1>

    <SteamApiGameCountRequest />
  </>);
}

function SteamApiGameCountRequest() {

  const [response, setResponse] = useState<any>({});
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    const getGames = async () => {
      const res = await axios.get('http://localhost:5173/GetOwnedGames', 
        { 
          params: {
            format: 'json',
            steamid: '76561198194449583'
      }});
      
      setResponse(res.data);
      setLoading(false);
    }

    getGames();
  }, []);

  if (loading) {
    return (<p>Loading...</p>);
  } else {
    return (<p>I have {response.response.game_count} games</p>);
  }
}

export default App;

However, there is a lot more boiler-plate code involved and I am planning on using a lot more api calls in my app so it would be nicer if I could use the new hook.

I feel like the answer to this question will most likely be just to use React 18 until Vite updates, as Vite doesn't currently support React 19, but if I am doing something wrong an answer would be greatly appreciated.

本文标签: javascriptReact 1939s use() Hook not functioning as intended with the latest version of ViteStack Overflow