qmining-page/src/pages/_app.js
2022-03-17 17:35:49 +01:00

95 lines
2.3 KiB
JavaScript

import React, { useState, useEffect } from 'react'
import Head from 'next/head'
import Layout from '../components/layout'
import '../defaultStyles.css'
import constants from '../constants.json'
function MyApp({ Component, pageProps, router }) {
const [userId, setUserId] = useState()
const [motd, setMotd] = useState()
const [unreads, setUnreads] = useState()
const [globalState, setGlobalState] = useState({})
const getGlobalProps = () => {
fetch(`${constants.apiUrl}infos?motd=true`, {
credentials: 'include',
Accept: 'application/json',
'Content-Type': 'application/json',
})
.then((resp) => {
return resp.json()
})
.then((data) => {
fetch(`${constants.apiUrl}hasNewMsg?userid=${data.uid}`, {
credentials: 'include',
Accept: 'application/json',
'Content-Type': 'application/json',
})
.then((resp) => {
return resp.json()
})
.then((hasNewMsg) => {
const res = { ...data, ...hasNewMsg }
setUserId(res.uid)
setMotd(res.motd)
setUnreads(res.unreads)
})
.catch((err) => {
const res = { ...data }
setUserId(res.uid)
setMotd(res.motd)
console.error('Error getting unreads')
console.error(err)
})
})
}
useEffect(() => {
getGlobalProps()
}, [])
const updateGlobalState = (newState) => {
setGlobalState({
...globalState,
...newState,
})
}
const globalData = {
userId: userId,
motd: motd,
unreads: unreads,
}
return (
<>
<Head>
<meta
name="viewport"
content="initial-scale=0.8, width=device-width, user-scalable=no"
/>
</Head>
<Layout
router={router}
globalData={globalData}
refetchGlobalData={getGlobalProps}
setGlobalState={updateGlobalState}
globalState={globalState}
>
<Component
{...pageProps}
router={router}
globalData={globalData}
refetchGlobalData={getGlobalProps}
setGlobalState={updateGlobalState}
globalState={globalState}
/>
</Layout>
</>
)
}
export default MyApp