Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to set useState variable in async method

I'm getting proper text from the method loadFIle. But when I try to set the state using setCodeToBeDsiplayed with the returned text, its not getting stored. It is giving empty string in the very next line.

const [CodeToBeDsiplayed, setCodeToBeDsiplayed] = useState("")

const [codeVersion, setCodeVersion] = useState(exampleCodeJava8);

 useEffect( () => {
        (async()=>{
            var text=await loadFile(exampleCodeJava8);
            setCodeToBeDsiplayed(text);
            setCodeVersion(CodeToBeDsiplayed);  
        })()
       
    }, [])

loadFile()

async function loadFile(url) {
        console.log("Dowloading file : " + url);

        return new Promise((resolve,reject)=>{
            var json;
            var xhr = new XMLHttpRequest();
            xhr.responseType = 'text';
                xhr.onload =(event)=>{
                    json = xhr.response;
                    console.log("json : " + json);
                    resolve(json);
                };
                xhr.error=(error)=>{
                    reject(error);
                }
            xhr.open('GET', url);
            xhr.send();
        });
like image 536
HarshEc Avatar asked Jan 29 '26 06:01

HarshEc


1 Answers

useState is an async function and it also does not return a Promise. Using async/await or anything similar will not work. You need to use useEffect and add the dependency to invoke the other state to be set.

useEffect(() => { setCodeVersion(CodeToBeDsiplayed);}, [CodeToBeDsiplayed])
like image 193
Ayaz Avatar answered Jan 31 '26 20:01

Ayaz