-
Notifications
You must be signed in to change notification settings - Fork 2
/
store.js
76 lines (71 loc) · 2.35 KB
/
store.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
import React, { createContext, useContext, useState } from "react";
import { LogBox } from 'react-native';
import firebase from "./firebase.js";
const db = firebase.database();
export const StoreContext = createContext([]);
const StateProvider = ({ children }) => {
const [isSignedIn,setIsSignedIn] = useState(false);
const [username,setUsername] = useState('');
const [score, setScore] = useState(0);
const login = (username,password) =>{
db.ref().child("users").child(username).once('value',
function(snapshot) {
if (snapshot.exists()) {
if(snapshot.val().password === password){
setUsername(username);
setScore(snapshot.val().score);
setIsSignedIn(true);
}
else {
alert("username and password do not match")
}
}
else {
let alertStr = "username: " + username + " does not exist";
alert(alertStr)
}
})
.catch(function(error) {
//console.error(error);
});
};
const signUp =(username,password) => {
db.ref().child("users").child(username).once('value',
function(snapshot) {
if (snapshot.exists()) {
alert("username already exists!")
}
else {
db.ref('users/' + username)
.set({
password: password,
score: 0,
});
setUsername(username);
setScore(0);
setIsSignedIn(true);
}
})
.catch(function(error) {
//console.error(error);
});
};
return (
<StoreContext.Provider
value={{
username,
setUsername,
score,
setScore,
isSignedIn,
setIsSignedIn,
login,
signUp
}}
>
{children}
</StoreContext.Provider>
);
};
export default StateProvider;
export const useStore = () => useContext(StoreContext);