简体   繁体   中英

How to check id IndexedDB already exist inside of React lifecycle methods

I have react.js component where I want to check if IndexedDB exists.

I am trying to do this

componentDidMount() {
    var dbExists = true;
    var openReq = indexedDB.open("dbName");
    openReq.onupgradeneeded = e => {
      e.target.transaction.abort();
      dbExists = false;

      console.log("Does not exist");
      this.setState({redirect: false})
    };

    if (dbExists) {
      this.setState({redirect: true})
    }
  }

But it does not work as expected - even if IndexedDB with name dbName exists it shows this line console.log("Does not exist"); Would you be so kind to give me any advice about how to check if DB exists ?
Thank you in advanced!

IndexedDB is async and your code is checking dbExist in sync way so it wont work. You can use localStorage to set value - so when db is created you set value to true and by default set it to false in start of your application.

so at start of your app, you need to execute below code -

var isDbCreated = localStorage.getItem('is_db_created')==='true';
if(!isDbCreated){
    localStorage.setItem('is_db_created','false');
}

and inside onupgradeneeded when db is created you set it to true -

localStorage.setItem('is_db_created','true');

If you are finding it tough - consider using jsstore library - it gives api to check whether db is created or not and also it provides simple sql like api for almost all db functionalities.

Check it out react example for more info - https://github.com/ujjwalguptaofficial/JsStore/tree/master/examples/react

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