IndexedDB-从数据库获取对象并将其存储

时间:2020-09-16 09:46:53

标签: javascript reactjs indexeddb

我已经创建了一个简单的待办事项列表,并希望将其存储在IndexedDB中。 当存储功能正常运行时,get功能不起作用。
我试图将对象存储在名为arr的变量中并返回它。 我的猜测是,由于IndexedDB是异步工作的,因此该函数不返回任何内容,因为Todo尚未存储在arr中。

有人可以告诉我是否确实如此,如果可以,我该如何解决? 我是一个绝对的初学者,不到一个星期前才开始使用React。

import React, {useState, useEffect} from 'react';
import Todo from './components/Todo'
import Form from './components/Form'
import './index.css';

const DEFAULT_KEY = "default";

const putDatabase = (todo) => {

  let request = window.indexedDB.open('Database', 1),
      db,
      tx,
      store;
  
  request.onupgradeneeded = (e) => {
      let db = request.result,
      store = db.createObjectStore('todo', {keyPath: 'id'});
  }

  request.onerror = (e) => { console.log('error' + e.target.errorCode)};

  request.onsuccess = (e) => {
      db = request.result;
      tx = db.transaction('todo', 'readwrite');
      store = tx.objectStore('todo');

      db.onerror = (e) => {console.log('error')};

      todo = JSON.stringify(todo);
      store.put({id: DEFAULT_KEY, value: todo});
      tx.oncomplete = () => { db.close() };
      }
}


const getDatabase = () => {

  let request = window.indexedDB.open('Database', 1),
      db,
      tx,
      store;

  request.onupgradeneeded = (e) => {
      let db = request.result,
          store = db.createObjectStore('todo', {autoIncrement: true});
  }

  request.onerror = (e) => {console.log('error' + e.target.errorCode)};
  
  request.onsuccess = (e) => {
      db = request.result;
      tx = db.transaction('todo', 'readonly');
      store = tx.objectStore('todo');

      db.onerror = (e) => {console.log('error')};

      let arr = store.get(DEFAULT_KEY);
      arr.onsuccess = () => {
        //const array = arr.result;
        return arr.result.value;   
      }

      tx.oncomplete = () => {db.close()};   
  }
}


const App = () => {

const [todos, setTodos] = useState([]);

useEffect(() => {
  getDatabase();
}, [])


const addTodo = text => {
  const newTodos = [... todos, {text}];
  setTodos(newTodos);
  putDatabase(newTodos);
};

function completeTodo(index){
  const newTodos = [... todos];
  newTodos[index].isCompleted = true;
  putDatabase(newTodos);
};

const removeTodo = (index) => {
  const newTodos = [...todos];
  newTodos.splice(index, 1);
  setTodos(newTodos);
  putDatabase(newTodos);
}


  return(

    <div className ="app">
      <div className="todo-app">
        <h1>ToDo's</h1>

        {todos.map( (todo, index) => (
          <Todo
            key = {index}
            index={index}
            todo = {todo}
            completeTodo={completeTodo}
            removeTodo={removeTodo}
            />
  ))}
        
      <Form addTodo={addTodo} />
      </div>
    </div>
  );
}



export default App;

0 个答案:

没有答案