Setup my sqlite database on userdata path on electron - database
I managed to copy my database (included in my application) directly into the userdata folder.
but I would like to setup my database directly from this folder in my file dedicated to the sql query.
but with the contextisolation impossible to do it. I tried with the contextBridge and I manage to retrieve the folder path from my index.html but not from my js file.
Can anyone help me?
Main.js
const { app, BrowserWindow, ipcMain } = require("electron");
const { dirname } = require("path");
const path = require("path");
const fs = require("fs");
const { electron } = require("process");
const { URLSearchParams } = require("url");
const ipc = ipcMain;
process.env['ELECTRON_DISABLE_SECURITY_WARNINGS'] = 'true';
// Window
function createWindow() {
const win = new BrowserWindow({
width: 1600,
height: 900,
minWidth: 1024,
minHeight: 640,
closable: true,
darkTheme: true,
frame: false,
icon: path.join(__dirname, "./images/ico.ico"),
webPreferences: {
nodeIntegration: true,
contextIsolation: true,
//devTools: true,
preload: path.join(__dirname, "preload.js"),
},
});
win.loadFile("index.html");
//win.webContents.openDevTools();
ipc.on("app/close", () => {
app.quit()
})
ipc.on("app/minimize", () => {
win.minimize()
})
ipc.on("app/reload", () => {
win.reload()
})
ipc.on("app/size", () => {
if (win.isMaximized()) {
win.restore();
win.resizable = true
} else {
win.maximize();
win.resizable = false
}
})
}
// When Electron Ready
app.whenReady().then(() => {
createWindow();
app.on("activate", () => {
if (BrowserWindow.getAllWindows().length === 0) {
createWindow();
}
});
});
app.on("window-all-closed", () => {
if (process.platform !== "darwin") {
app.quit();
}
});
preload.js
const {ipcRenderer, contextBridge} = require("electron");
const db = require("./js/db");
const getNbonus = () => {
return db.getNbonus();
}
const getTotalCost = () => {
return db.getTotalCost();
}
const getTotalWin = () => {
return db.getTotalWin();
}
const getProfitLoss = () => {
return db.getProfitLoss();
}
const newHunt = (title,start,date) => {
db.newHunt(title,start,date);
}
const date = () => {
return db.date();
}
const ProfitLoss = () => {
return db.ProfitLoss();
}
const bonushunt = () => {
return db.bonushunt();
}
const deletehunt = (id) => {
db.deletehunt(id);
}
const updatehunt = (title,start,date,id) => {
db.updatehunt(title,start,date,id);
}
const ProfitLossbyid = (id) => {
db.ProfitLossbyid(id);
return db.ProfitLossbyid(id);
}
const CountBonusbyid = (id) => {
db.CountBonusbyid(id);
return db.CountBonusbyid(id);
}
const startbyid = (id) => {
db.startbyid(id);
return db.startbyid(id);
}
const hunt = (id) => {
db.hunt(id);
return db.hunt(id);
}
const slots = () => {
return db.slots();
}
const newbonus = (idhunt,slotid,betsize) => {
db.newbonus(idhunt,slotid,betsize);
}
const deletebonus = (id) => {
db.deletebonus(id);
}
const getidhunt = (title) => {
db.getidhunt(title);
return db.getidhunt(title);
}
const updatebonus = (idhunt,id,bet,payout) => {
db.updatebonus(idhunt,id,bet,payout);
}
const bonushuntpage = () => {
return db.bonushuntpage();
}
const avghuntwin = () => {
return db.avghuntwin();
}
const bestslot = (id) => {
db.bestslot(id);
return db.bestslot(id);
}
const worstslot = (id) => {
db.worstslot(id);
return db.worstslot(id);
}
const amountwon = (id) => {
db.amountwon(id);
return db.amountwon(id);
}
const avgrequire = (id) => {
db.avgrequire(id);
return db.avgrequire(id);
}
const avg = (id) => {
db.avg(id);
return db.avg(id);
}
const bex = (id) => {
db.bex(id);
return db.bex(id);
}
const avgx = (id) => {
db.avgx(id);
return db.avgx(id);
}
const remain = (id) => {
db.remain(id);
return db.remain(id);
}
const cent = (id) => {
db.cent(id);
return db.cent(id);
}
const allslot = () => {
return db.allslot();
}
const updateslot = (id,slot,provider,rtp,volatility,potential) => {
db.updateslot(id,slot,provider,rtp,volatility,potential);
}
const provider = () => {
return db.provider();
}
const providerbyid = (id) => {
db.providerbyid(id)
return db.providerbyid(id);
}
const newslot = (slot,provider,rtp,volatility,potential) => {
db.newslot(slot,provider,rtp,volatility,potential);
}
const API = {
window: {
close: () => ipcRenderer.send("app/close"),
minimize: () => ipcRenderer.send("app/minimize"),
size: () => ipcRenderer.send("app/size"),
reload: () => ipcRenderer.send("app/reload")
}
}
contextBridge.exposeInMainWorld("app", API)
contextBridge.exposeInMainWorld("api", {
getNbonus: getNbonus,
getTotalCost: getTotalCost,
getTotalWin: getTotalWin,
getProfitLoss: getProfitLoss,
newHunt: newHunt,
date: date,
bonushunt: bonushunt,
deletehunt: deletehunt,
ProfitLoss: ProfitLoss,
updatehunt: updatehunt,
ProfitLossbyid: ProfitLossbyid,
CountBonusbyid: CountBonusbyid,
startbyid: startbyid,
hunt: hunt,
slots: slots,
newbonus: newbonus,
deletebonus: deletebonus,
getidhunt: getidhunt,
updatebonus: updatebonus,
bonushuntpage: bonushuntpage,
avghuntwin: avghuntwin,
bestslot: bestslot,
worstslot: worstslot,
amountwon: amountwon,
avgrequire: avgrequire,
avg: avg,
bex: bex,
avgx: avgx,
remain: remain,
cent: cent,
allslot: allslot,
updateslot: updateslot,
provider: provider,
providerbyid: providerbyid,
newslot: newslot
})
db.js
const database = require('better-sqlite3-multiple-ciphers')
const db = new database('bh.db')
exports.getNbonus = () => {
const stmt = db.prepare('SELECT count(*) as nbonus FROM bonus_hunt');
const res = stmt.all();
return res;
}
exports.getTotalCost = () => {
const stmt = db.prepare('SELECT SUM(start) as totalcost FROM bonus_hunt');
const res = stmt.all();
return res;
}
exports.getTotalWin = () => {
const stmt = db.prepare('SELECT SUM(payout) as totalwin FROM hunt');
const res = stmt.all();
return res;
}
exports.getProfitLoss = () => {
const stmt = db.prepare('SELECT ((SELECT SUM(payout) as totalwin FROM hunt)-(SELECT SUM(start) as totalcost FROM bonus_hunt)) as ProfitLoss');
const res = stmt.all();
return res;
}
exports.newHunt = (title,start,date) => {
const sql = db.prepare('INSERT INTO bonus_hunt (title,start,date) VALUES (:title, :start, :date)');
sql.run({title,start,date})
}
exports.date = () => {
const stmt = db.prepare('SELECT date FROM bonus_hunt');
const res = stmt.all();
return res;
}
exports.ProfitLoss = () => {
const stmt = db.prepare('SELECT ((SELECT SUM(payout) FROM hunt where hunt.id_bonushunt = bonus_hunt.id)-(SELECT start FROM bonus_hunt where bonus_hunt.id = hunt.id_bonushunt)) as profitloss from bonus_hunt JOIN hunt on bonus_hunt.id = hunt.id_bonushunt GROUP BY id');
const res = stmt.all();
return res;
}
exports.bonushunt = () => {
const stmt = db.prepare('SELECT id, title, start,date,(Select count(*) from hunt where hunt.id_bonushunt = bonus_hunt.id) as nbbonus, ((SELECT SUM(payout) FROM hunt where hunt.id_bonushunt = bonus_hunt.id)-(SELECT start FROM bonus_hunt where bonus_hunt.id = hunt.id_bonushunt)) as profitloss from bonus_hunt JOIN hunt on bonus_hunt.id = hunt.id_bonushunt GROUP BY id');
const res = stmt.all();
return res;
}
exports.deletehunt = (id) => {
const stmt = db.prepare('DELETE from bonus_hunt WHERE id=:id');
stmt.run ({id})
}
exports.updatehunt = (title,start,date,id) => {
const sql = db.prepare('UPDATE bonus_hunt SET title=:title, start=:start, date=:date WHERE id=:id');
sql.run({title,start,date,id})
}
exports.ProfitLossbyid = (id) => {
const stmt = db.prepare('SELECT id, ((SELECT SUM(payout) FROM hunt where hunt.id_bonushunt = bonus_hunt.id)-(SELECT start FROM bonus_hunt where bonus_hunt.id = hunt.id_bonushunt)) as profitloss from bonus_hunt JOIN hunt on bonus_hunt.id = hunt.id_bonushunt WHERE id=:id GROUP BY id');
const res = stmt.all({id});
return res
}
exports.CountBonusbyid = (id) => {
const stmt = db.prepare('SELECT count(*) as NB_Bonus FROM hunt where id_bonushunt=:id');
const res = stmt.all({id});
return res
}
exports.startbyid = (id) => {
const stmt = db.prepare('SELECT start FROM bonus_hunt where id=:id');
const res = stmt.all({id});
return res
}
exports.hunt = (id) => {
const stmt = db.prepare('SELECT hunt.id_bonushunt as idhunt, hunt.id_slots as id, slots.slot, slots.provider, hunt.bet_size, hunt.payout, hunt.multiplier from hunt join slots on hunt.id_slots = slots.id where id_bonushunt=:id');
const res = stmt.all({id});
return res
}
exports.slots = () => {
const stmt = db.prepare('select id, slot FROM slots');
const res = stmt.all();
return res
}
exports.newbonus = (idhunt,slotid,betsize) => {
const sql = db.prepare('INSERT INTO hunt (id_bonushunt,id_slots,bet_size) VALUES (:idhunt, :slotid, :betsize)');
sql.run({idhunt,slotid,betsize})
}
exports.deletebonus = (id) => {
const stmt = db.prepare('DELETE from hunt WHERE id_slots=:id');
stmt.run ({id})
}
exports.getidhunt = (title) => {
const stmt = db.prepare('SELECT id from bonus_hunt where title=:title');
const res = stmt.all({title});
return res
}
exports.updatebonus = (idhunt,id,bet,payout) => {
const sql = db.prepare('UPDATE hunt SET bet_size=:bet, payout=:payout WHERE id_bonushunt=:idhunt and id_slots=:id');
sql.run({idhunt,id,bet,payout})
}
exports.bonushuntpage = () => {
const stmt = db.prepare('SELECT id, title, start,date,(Select count(*) from hunt where hunt.id_bonushunt = bonus_hunt.id) as nbbonus from bonus_hunt group by id');
const res = stmt.all();
return res;
}
exports.avghuntwin = () => {
const stmt = db.prepare('SELECT ((Select sum(payout))/(Select count(*))/(Select count(*) from bonus_hunt)) as avg from hunt');
const res = stmt.all();
return res;
}
exports.bestslot = (id) => {
const stmt = db.prepare('select slot,max(payout) as best from (select payout, slots.slot, bonus_hunt.id from hunt join slots on hunt.id_slots = slots.id join bonus_hunt on hunt.id_bonushunt = bonus_hunt.id) where id=:id');
const res = stmt.all({id});
return res
}
exports.worstslot = (id) => {
const stmt = db.prepare('select slot,min(payout) as worst from (select payout, slots.slot, bonus_hunt.id from hunt join slots on hunt.id_slots = slots.id join bonus_hunt on hunt.id_bonushunt = bonus_hunt.id) where id=:id');
const res = stmt.all({id});
return res
}
exports.amountwon = (id) => {
const stmt = db.prepare('select sum(payout) as amountwon from hunt where id_bonushunt=:id');
const res = stmt.all({id});
return res
}
exports.avgrequire = (id) => {
const stmt = db.prepare('SELECT ((bonus_hunt.start - SUM(hunt.payout)) / (SELECT COUNT(*) FROM hunt WHERE hunt.payout IS NULL)) as BE FROM hunt JOIN bonus_hunt on bonus_hunt.id = hunt.id_bonushunt where id_bonushunt=:id');
const res = stmt.all({id});
return res
}
exports.avg = (id) => {
const stmt = db.prepare('SELECT avg(hunt.payout) as AVG FROM hunt where id_bonushunt=:id');
const res = stmt.all({id});
return res
}
exports.bex = (id) => {
const stmt = db.prepare('SELECT ((SELECT ((bonus_hunt.start - SUM(hunt.payout)) / (SELECT COUNT(*) FROM hunt WHERE hunt.payout IS NULL)) FROM hunt JOIN bonus_hunt on bonus_hunt.id = hunt.id_bonushunt where id_bonushunt=:id) / avg(hunt.bet_size)) as BEX FROM hunt WHERE hunt.payout IS NULL');
const res = stmt.all({id});
return res
}
exports.avgx = (id) => {
const stmt = db.prepare('SELECT avg(hunt.multiplier) as AVGX FROM hunt where id_bonushunt=:id');
const res = stmt.all({id});
return res
}
exports.remain = (id) => {
const stmt = db.prepare('SELECT COUNT(*) as Remain FROM hunt WHERE hunt.payout IS NULL and id_bonushunt=:id');
const res = stmt.all({id});
return res
}
exports.cent = (id) => {
const stmt = db.prepare('SELECT COUNT(*) as cent FROM hunt WHERE hunt.multiplier >= 100 and id_bonushunt=:id');
const res = stmt.all({id});
return res
}
exports.allslot = () => {
const stmt = db.prepare('SELECT id,slot,provider,rtp,volatility,potential from slots');
const res = stmt.all();
return res;
}
exports.updateslot = (id,slot,provider,rtp,volatility,potential) => {
const sql = db.prepare('UPDATE slots SET slot=:slot, provider=:provider, rtp=:rtp, volatility=:volatility, potential=:potential WHERE id=:id');
sql.run({id,slot,provider,rtp,volatility,potential})
}
exports.provider = () => {
const stmt = db.prepare('SELECT id, provider from slots group by provider');
const res = stmt.all();
return res;
}
exports.providerbyid = (id) => {
const stmt = db.prepare('SELECT provider FROM slots where id=:id');
const res = stmt.all({id});
return res
}
exports.newslot = (slot,provider,rtp,volatility,potential) => {
const sql = db.prepare('INSERT INTO slots (slot,provider,rtp,volatility,potential) VALUES (:slot, :provider, :rtp, :volatility, :potential)');
sql.run({slot,provider,rtp,volatility,potential})
}
i want to get userdata path for my database
Related
how to auto delete data after new data has been uploaded on firebase on react?
When a user updates their profile photo I want old data to be overwritten on firestore. I'm using firebase storage to store photos and upload firebase URL to restore database so I tried filtering in on the front end side but I have multiple users to filter and there are a lot of duplicates here is whole functionality of uploading data to firestore storage then updating firestore db and then pulling data with use const [userImg, setUserImg] = useState() const [image, setImage] = useState(null) const [htlmImg, setHtmlImg] = useState(null) const [url, setUrl] = useState(null) const [userName, setUserName] = useState(null) const [sureLoading, setSureLoading] = useState(false) const [photoEdit, setPhotoEdit] = useState(false) const handleImageChange = (e) => { if (e.target.files[0]) { setImage(e.target.files[0]) setHtmlImg(URL.createObjectURL(e.target.files[0])) } } const uploadImg = () => { const imageRef = ref(storage, `image${user.uid}`) uploadBytes(imageRef, image) .then(() => { getDownloadURL(imageRef) .then((url) => { setUrl(url) }) .catch((error) => { console.log(error.message, 'error getting the image url') }) setImage(null) }) .catch((error) => { console.log(error.message) }) setSureLoading(true) } const handlePfpSubmit = async () => { const { uid } = user if (url !== null) { try { await addDoc(collection(db, 'user'), { pfp: url, userName, uid, timestamp: serverTimestamp(), time: Date(), }) if (!photoEdit) { navigate('/test') } console.log('data send') } catch (err) { console.log(err) } } } const [displayName, setDisplayName] = useState(null) const [displayPhoto, setDisplayPhoto] = useState(null) const [userProfiles, setUserProfiles] = useState(null) useEffect(() => { const q = query(collection(db, 'user'), orderBy('timestamp')).update() const unsub = onSnapshot(q, (querySnapShot) => { let photo = [] querySnapShot.forEach((doc) => { photo.push({ ...doc.data(), id: doc.id }) }) console.log(photo) console.log('data resived') let userUid = photo .filter((item) => { if (user.uid === item.uid) { return item.uid } }) .map((item) => { const { pfp } = item return pfp }) setDisplayPhoto( userUid.filter((val, index) => { if (userUid.length - 1 <= index) { return val } }), ) let userUidName = photo .filter((item) => { if (user.uid === item.uid) { return item.uid } }) .map((item) => { const { userName } = item return userName }) let photoFilter = userUidName.filter((val, index) => { if (userUidName.length - 1 <= index) { return val } }) setDisplayName(photoFilter) setUserProfiles(photo) console.log(displayPhoto) }) console.log('re render ? ') return () => unsub() }, [user])
issue with Stripe_success _url with Multiple Destination Product Ids
Please I need assistance with a code. I have a Nextjs dynamic page as my 'stripe_success_url' Initially I had one product 'courses' whose {id} is beign fetched in the router.query however, i have created a new product 'ebook' whose {id} is also being fetched in the router.query I edited the code to differentiate course ID and ebook ID but it is not working yet. const StripeSuccess = () => { // state const [course, setCourse] = useState([]); const [ebook, setEbook] = useState([]); const router = useRouter(); const { id } = router.query; useEffect(() => { const fetchCourses = async () => { const { data } = await axios.get('/api/courses'); setCourse(data); //console.log(data); }; fetchCourses(); }, [id]); useEffect(() => { const fetchEbooks = async () => { const { data } = await axios.get('/api/ebooks'); setEbook(data); //console.log(data); }; fetchEbooks(); }, [id]); useEffect(() => { if (id === `${course._id}`) { const successRequest = async () => { const { data } = await axios.get(`/api/stripe-success/${id}`); //console.log(data); //console.log('SUCCESS REQ DATA', data); router.push(`/user/course/${data.course.slug}`); }; successRequest(); } }, [id]); useEffect(() => { if (id === `${ebook._id}`) { const successEbookRequest = async () => { const { data } = await axios.get(`/api/stripe-ebooksuccess/${id}`); //console.log(data); //console.log('SUCCESS REQ DATA', data); router.push(`/user/course/${data.ebook.slug}`); }; successEbookRequest(); } }, [id]);
Getting a undefined value when trying to match fetch results to people objects
Im working on a star wars api app. I am getting an array of people objects, 10 characters. Who all are their own object with different values. However homeworld, and species are urls. So I have to fetch them and store that data to the correct place. I figured out a way to get the homeworld values to each character. However when I try to do it with species I receive undefined. Would appreciate any help this has been kind of a pain thanks ahead of time ! const [people, setPeople] = useState([]); const [homeWorld, setHomeWorld] = useState([]); const [species, setSpecies] = useState([]); const [nextPageUrl, setNextPageUrl] = useState("https://swapi.dev/api/people/"); const [backPageUrl, setBackPageUrl] = useState(''); const [test, setTest] = useState([]); const fetchPeople = async () => { const { data } = await axios.get(nextPageUrl); setNextPageUrl(data.next); setBackPageUrl(data.previous); return data.results; } const backPage = async () => { const { data } = await axios.get(backPageUrl); setCharacters(data.results); setNextPageUrl(data.next); setBackPageUrl(data.previous); } // Get People async function getPeople() { const persons = await fetchPeople(); const homeWorldUrl= await Promise.all( persons.map((thing) => axios.get(thing.homeworld)), ); const newPersons = persons.map((person) => { return { ...person, homeworld: homeWorldUrl.find((url) => url.config.url === person.homeworld) }; }); const newPersons2 = newPersons.map((person) => { return { ...person, homeWorld: person.homeworld.data.name }; }); setPeople(newPersons2); } // Get Species async function getSpecies() { const persons = await fetchPeople(); const speciesUrl = await Promise.all( persons.map((thing) => axios.get(thing.species)), ); const newSwapi = persons.map((person) => { return { ...person, species: speciesUrl.find((info) => info.data.url === person.species) }; }); setTest(newSwapi); // const newPersons2 = newPersons.map((person) => { // return { // ...person, // homeWorld: person.homeworld.data.name // }; // }); } useEffect(() => { getPeople(); getSpecies(); // eslint-disable-next-line react-hooks/exhaustive-deps }, []); ```
Species property of person is a array, so your getSpecies() should be like async function getSpecies() { const persons = await fetchPeople(); const speciesUrl = await Promise.all( persons .filter((thing) => thing.species.length) .map((thing) => axios.get(thing.species[0])) ); const newSwapi = persons.map((person) => { return { ...person, species: speciesUrl.find((info) => info.data.url === person.species[0]) }; }); setTest(newSwapi); }
Component rerendering in reactjs
I am working on react app where one of my component when I place console.log('Hello') it keeps on re-rendering. I am not sure why. This is How my component looks. Any help would be great DispensingIncident.jsx const DispensingIncidents = (props) => { const classes = useStyles(); const { getFilterData, dispensingData, getPeriodList, getTypeList, getOverviewData, location, history, } = props; const [timeSpan, setTimeSpan] = React.useState("Monthly"); const [year, setYear] = React.useState(2020); const [tabValue, setTabValue] = React.useState(0); const [spanData, setSpanData] = React.useState([]); const [dataType, setDataType] = React.useState("aim"); const { loading, duration, period, type, dispensingOverviewData, overviewDataLoading, } = dispensingData; const { count } = dispensingOverviewData; // console.log("props", duration["monthly"][0].period); console.log("Hellowo"); useEffect(() => { getPeriodList(); getTypeList(); // eslint-disable-next-line }, []); useEffect(() => { history.replace({ pathname: location.pathname, search: `?year=${year}&period=${timeSpan}`, }); setYear(year); setTimeSpan(timeSpan); // eslint-disable-next-line }, [year, timeSpan]); useEffect(() => { getFilterData(year); // eslint-disable-next-line }, [year]); /** * GET query from url search param * #usage query.get("year") */ function useQuery() { return new URLSearchParams(location.search); } const query = useQuery(); /** * * #param {*} event * #param {*} newValue * on tab change */ // eslint-disable-next-line const handleTabChange = (event, newValue) => { setTabValue(newValue); }; /** * Year change * #param {*} event */ const handleYearChange = (event) => { setYear(event.target.value); setTimeSpan(query.get("period")); }; /** * Span change * #param {*} event */ const handleSpanChange = (event) => { const value = event.target.value; setTimeSpan(value); }; const time = query.get("period"); useEffect(() => { if (time === "Yearly") { const yearlyData = duration["yearly"]; setSpanData(yearlyData); } else if (time === "Weekly") { const weeklyData = duration["weekly"]; setSpanData(weeklyData); } else if (time === "Quarterly") { const quarterlyData = duration["quarterly"]; setSpanData(quarterlyData); } else if (time === "Monthly") { const monthlyData = duration["monthly"]; setSpanData(monthlyData); } else if (time === "6 months") { const halfYearlyData = duration["half-yearly"]; setSpanData(halfYearlyData); } }, [time, duration]); const handleSpanTabChange = (data) => { getOverviewData(year, data.period.to, data.period.from, dataType); }; const handleDataTypeChange = (event) => { setDataType(event.target.value); }; if (loading) { return ( <Loading/> ); } return ( <div className={classes.dispenseRoot}> <Paper elementType="div" elevation={5} square={true} variant="elevation" className={classes.topContainer} > // content here...... </Paper> </div> ); }; function mapStateToProps(state) { return { dispensingData: state.dispensing, }; } const mapDispatchToProps = (dispatch) => ({ getFilterData: (year) => dispatch({ type: GET_DISPENSING_INCIDENT_FILTER_DATA, year }), getPeriodList: () => dispatch({ type: GET_DISPENSING_INCIDENT_PERIOD_LIST }), getTypeList: () => dispatch({ type: GET_DISPENSING_INCIDENT_TYPE_LIST }), getOverviewData: (period, to, from, datatype) => dispatch({ type: GET_DISPENSING_OVERVIEW, period, from, to, datatype }), }); export default connect( mapStateToProps, mapDispatchToProps )(DispensingIncidents); This is what happeing when i put console.log('Hello')
Spotify player SDK in react
I am trying to implement Spotify player SDK in my react app. But I do not know it is giving me an error that Spotify is undefined. I am trying to implement the script in the useEffect hook in this context file. This is my context file and trying to set up player SDK in it. Thanks in advance. import React,{ createContext, useState,useEffect } from 'react' import { myPlaylist, fetchAnything } from "../../api-fetching/api-fetching" // Get the hash of the url const hash = window.location.hash .substring(1) .split("&") .reduce(function(initial, item) { if (item) { var parts = item.split("="); initial[parts[0]] = decodeURIComponent(parts[1]); } return initial; }, {}); window.location.hash = ""; export const MainContext = createContext(); const MainContextProvider = (props) => { const authEndPoint = 'https://accounts.spotify.com/authorize?'; // Replace with your app's client ID, redirect URI and desired scopes const clientId = "5c4e46e8acf24w794ru325qi535fw5325hsakf22be91378ff14"; let redirectUri = ""; if(process.env.NODE_ENV === "development") { redirectUri += "http://localhost:3000/"; } const scopes = [ "streaming", "user-read-email", "user-read-private", "user-read-currently-playing", "user-read-playback-state", "user-library-read", "playlist-read-collaborative", "playlist-read-private" ]; const [token, setToken] = useState(null); const [scriptLoading, setScriptLoading] = useState(true); const [currentUser, setCurrentUser] = useState(null); const [discover, setDiscover] = useState(null); const [discoverPlaylist, setDiscoverPlaylist] = useState(null); const [discoverPlaylistTracks, setDiscoverPlaylistTracks] = useState(null); const [userPlaylist, setUserPlaylist] = useState(null); const [ userPlaylistTracks ,setUserPlaylistTracks] = useState(null); const [artistInfo, setArtistInfo] = useState(null); const [albumTracks, setAlbumTracks] = useState(null); const [newReleases, setNewReleases] = useState(null); const [newReleasesTracks, setNewReleasesTracks] = useState(null); const [searchResult, setSearchResult] = useState(null); const [searchValue, setSearchValue] = useState(""); const [playlistTracks, setPlaylistTracks] = useState(null); useEffect(() => { let _token = hash.access_token; setToken(_token); fetchAnything(token, "https://api.spotify.com/v1/me", setCurrentUser); if(scriptLoading){ const script = document.createElement("script"); script.src = "https://sdk.scdn.co/spotify-player.js"; script.async = true; script.defer = true; document.body.appendChild(script); setScriptLoading(false); } window.onSpotifyWebPlaybackSDKReady = () => { const player = new Spotify.Player({ name: 'Web Playback SDK Quick Start Player', getOAuthToken: cb => { cb(token); } }); // Error handling player.addListener('initialization_error', ({ message }) => { console.error(message); }); player.addListener('authentication_error', ({ message }) => { console.error(message); }); player.addListener('account_error', ({ message }) => { console.error(message); }); player.addListener('playback_error', ({ message }) => { console.error(message); }); // Playback status updates player.addListener('player_state_changed', state => { console.log(state); }); // Ready player.addListener('ready', ({ device_id }) => { console.log('Ready with Device ID', device_id); }); // Not Ready player.addListener('not_ready', ({ device_id }) => { console.log('Device ID has gone offline', device_id); }); // Connect to the player! player.connect(); }; }, [token]) useEffect(() => { if(currentUser){ myPlaylist(token, setUserPlaylist, currentUser.id); } }, [currentUser, token]) return ( <MainContext.Provider value={{ currentUser,playlistTracks, setPlaylistTracks ,searchValue, setSearchValue,searchResult, setSearchResult,newReleasesTracks, setNewReleasesTracks ,newReleases, setNewReleases ,albumTracks, setAlbumTracks,artistInfo, setArtistInfo,discoverPlaylistTracks, setDiscoverPlaylistTracks,userPlaylistTracks, setUserPlaylistTracks, userPlaylist,discoverPlaylist,setDiscoverPlaylist,discover,setDiscover, token,setToken, authEndPoint, clientId, redirectUri, scopes }}> {props.children} </MainContext.Provider> ) } export default MainContextProvider
You must refer to the Player through a global object: window.onSpotifyWebPlaybackSDKReady = () => { const player = new window.Spotify.Player({ name: "Carly Rae Jepsen Player", getOAuthToken: (callback) => { callback("access token here"); }, volume: 0.5, }); };