简体   繁体   中英

Javascript---I have an api response which should come before anything else loads up or renders in the browser

JavaScript----.I have an api response which should come before anything else loads up or renders in the browser but it gives response which is slower than the loading of first component which rendered on the page. This the code for the api call which i make to get the data is given below.Is there any way i can make this given below to be executed synchronously.

const GetLanguageData =   (pageName) => {
const traslationApiUrlObj = {
languageCode: $('#hdnLanguageCode').val(),
baseUrl: `${apiUrl}`,
page: pageName
}
const { baseUrl, languageCode, page } = traslationApiUrlObj;
const traslationApiUrl = `${baseUrl}${languageCode}/${page}`;
ResourceLanguageText = null;
fetch(traslationApiUrl)
    .then(res => res.json())
    .then((result) => {
        ResourceLanguageText = result;
        console.log('Result');
    },
        (error) => {
            console.log(error);
        });

}

it can be achieved using combination of state and componentdidmount() lifecycle method.

keep a boolean flag in state "loaded" initialized to true.

call api in componentdidmount(), after you receive response set "loaded" to true in state.

in your render() method, do a conditional render based on your loaded is true

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM