-
-
Save Iheanacho-ai/656f05b6e98ca1422633b112f85b37f8 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { useState, useEffect } from 'react'; | |
import { Appwrite } from 'appwrite'; | |
import { ToastContainer, toast } from 'react-toastify'; | |
import 'react-toastify/dist/ReactToastify.css'; | |
import './App.css'; | |
const App = () => { | |
const [theArray, setTheArray] = useState([]); | |
const [response, setResponse] = useState('Welcome!'); | |
const notify = (response) => { | |
toast(response) | |
}; | |
// Init your Web SDK | |
const sdk = new Appwrite(); | |
sdk | |
.setEndpoint('http://localhost/v1') // Your Appwrite Endpoint | |
.setProject(projectID) // Your project ID | |
; | |
async function createAnonymousSession(){ | |
try{ | |
await sdk.account.createAnonymousSession(); | |
}catch(err){ | |
console.log(err) | |
} | |
} | |
useEffect(()=> { | |
createAnonymousSession(); | |
if(sdk.account.get !== null){ | |
try { | |
sdk.subscribe('collections.[collectionID].documents', response => { | |
setResponse(`The Appwrite ${response.event} event was called`) | |
}); | |
} catch (error) { | |
console.log(error, 'error') | |
} | |
} | |
}, []) | |
const listDocuments = async() => { | |
try { | |
let response = await sdk.database.listDocuments(collectionID); | |
response.documents.map(document => setTheArray(prevArray => [...prevArray, document.$id]) ) | |
} catch (error) { | |
console.log(error); | |
} | |
} | |
const createDocument = async () => { | |
try{ | |
await sdk.database.createDocument(collectionID, "unique()", { | |
"message": "Hello World!", | |
}); | |
listDocuments() | |
}catch(error){ | |
console.log(error) | |
} | |
} | |
const deleteDocument = async () => { | |
if (theArray.length > 0) { | |
try { | |
let documentID = theArray[theArray.length - 1] | |
await sdk.database.deleteDocument(collectionID, documentID); | |
listDocuments(); | |
} catch (error) { | |
console.log(error) | |
} | |
} else { | |
alert('database is empty') | |
} | |
} | |
useEffect(() => { | |
notify(response); | |
}, [response]); | |
return ( | |
<div className="App"> | |
<button type='button' onClick={createDocument}>Create Document</button> | |
<button type='button' onClick={deleteDocument}>Delete Document</button> | |
<ToastContainer/> | |
</div> | |
); | |
} | |
export default App; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment