2021年4月11日星期日

ReactJS - async function in useEffect doesn't wait under any condition

I have searched through possible solutions quite a bit and can't find any mistake that applies in this case. The await used inside useEffect just doesn't wait.

App.js: the data state is set only through default value and nowhere else

  const [data, setData] = useState( new Data() );      useEffect(()=>{      async function loadData() {        await data.load();      }      loadData().then(()=>{ console.log('Loaded!') });    }, [data])  

data.js is ES6 class that has async method load():

async load() {          let test = await fetch("https://raw.githubusercontent.com/json-iterator/test-data/master/large-file.json");          let testJson = await test.json();      }  

Whatever I try, the .then() is triggered within a split second, while opening the same json file in browser takes a long time.

Things I tried:

  • Using null as default state and instead initializing on mount useEffect( ()=>{setData( new Data() )}, [] ) (while adding check at top of data's useEffect to return if data is null)
  • IIFE function inside data's useEffect using just await instead of then
  • There are no fetching related warnings or errors in console, still I tried with just setTimeout instead
  • Few other probably pointless things.. I can't figure out what is wrong here.
https://stackoverflow.com/questions/67051543/reactjs-async-function-in-useeffect-doesnt-wait-under-any-condition April 12, 2021 at 09:04AM

没有评论:

发表评论