portfolio/src/store/AppProvider.jsx

75 lines
1.8 KiB
React
Raw Normal View History

2019-04-16 21:21:01 +02:00
import React, { PureComponent } from 'react'
import PropTypes from 'prop-types'
2019-11-09 19:12:58 +01:00
import Context from './createContext'
2019-04-16 21:21:01 +02:00
import { getLocationTimes } from '../utils/getLocationTimes'
import { getCountry } from '../utils/getCountry'
export default class AppProvider extends PureComponent {
2019-05-26 16:55:56 +02:00
static propTypes = {
children: PropTypes.any.isRequired
}
2019-04-16 21:21:01 +02:00
state = {
2019-11-09 19:12:58 +01:00
darkMode: false,
2019-05-26 23:52:27 +02:00
toggleDark: () => this.toggleDark(),
2019-05-25 13:26:57 +02:00
geolocation: null
2019-04-16 21:21:01 +02:00
}
store = typeof localStorage === 'undefined' ? null : localStorage
mounted = false
async componentDidMount() {
this.mounted = true
2019-05-26 16:55:56 +02:00
2019-05-25 13:26:57 +02:00
const geolocation = await getCountry()
this.setState({ geolocation })
2019-04-16 21:21:01 +02:00
this.checkDark()
}
componentWillUnmount() {
this.mounted = false
}
2019-11-09 19:12:58 +01:00
setDark(darkMode) {
this.mounted && this.setState({ darkMode })
2019-04-16 21:21:01 +02:00
}
darkLocalStorageMode(darkLocalStorage) {
2019-05-26 16:55:56 +02:00
darkLocalStorage === 'true' ? this.setDark(true) : this.setDark(false)
2019-04-16 21:21:01 +02:00
}
//
// All the checks to see if we should go dark or light
//
async checkTimes() {
2019-11-09 19:12:58 +01:00
const { geolocation, darkMode } = this.state
const { sunset, sunrise } = getLocationTimes(geolocation)
2019-04-16 21:21:01 +02:00
const now = new Date().getHours()
const weWantItDarkTimes = now >= sunset || now <= sunrise
2019-11-09 19:12:58 +01:00
!darkMode && weWantItDarkTimes ? this.setDark(true) : this.setDark(false)
2019-04-16 21:21:01 +02:00
}
async checkDark() {
2019-11-09 19:12:58 +01:00
const darkLocalStorage = await this.store.getItem('darkMode')
2019-04-16 21:21:01 +02:00
darkLocalStorage
? this.darkLocalStorageMode(darkLocalStorage)
: this.checkTimes()
}
toggleDark = () => {
2019-11-09 19:12:58 +01:00
this.setState({ darkMode: !this.state.darkMode })
this.store && this.store.setItem('darkMode', !this.state.darkMode)
2019-04-16 21:21:01 +02:00
}
render() {
2019-11-09 19:12:58 +01:00
return (
<Context.Provider value={this.state}>
{this.props.children}
</Context.Provider>
)
2019-04-16 21:21:01 +02:00
}
}