Skip to content
Permalink
Browse files

Refactor to custom hook

  • Loading branch information...
wgao19 committed May 23, 2019
1 parent fdc8d10 commit dfa93308c034afb9cd502137f19f0c7833dc3a7f
Showing with 24 additions and 19 deletions.
  1. +3 −19 src/components/SunMoonToggle/index.js
  2. +21 −0 src/components/SunMoonToggle/useTheme.js
@@ -1,26 +1,10 @@
import React, { useState, useEffect } from 'react'
import React from 'react'
import cx from 'classnames'
import { useTheme, THEMES } from './useTheme'
import s from './s.module.scss'

const THEMES = ['sun', 'moon']
const getNewTheme = currentTheme =>
THEMES.indexOf(currentTheme) >= 0
? THEMES[1 - THEMES.indexOf(currentTheme)]
: THEMES[0]

const SunMoonToggle = () => {
const [theme, setTheme] = useState(
typeof window !== 'undefined'
? window.localStorage.getItem('theme')
: THEMES[0]
)
const toggleTheme = currentTheme => {
const newTheme = getNewTheme(currentTheme)
setTheme(newTheme)
}
useEffect(() => {
typeof window !== 'undefined' && window.localStorage.setItem('theme', theme)
}, [theme])
const { theme, toggleTheme } = useTheme()
return (
<React.Fragment>
<div
@@ -0,0 +1,21 @@
import { useState, useEffect } from 'react'

export const THEMES = ['sun', 'moon']
const getNewTheme = currentTheme =>
THEMES.indexOf(currentTheme) >= 0
? THEMES[1 - THEMES.indexOf(currentTheme)]
: THEMES[0]

export const useTheme = () => {
const currentTheme =
typeof window !== 'undefined' ? window.localStorage.getItem('theme') : null
const [theme, setTheme] = useState(currentTheme || THEMES[0])
useEffect(() => {
typeof window !== 'undefined' && window.localStorage.setItem('theme', theme)
}, [theme])
const toggleTheme = currentTheme => {
const newTheme = getNewTheme(currentTheme)
setTheme(newTheme)
}
return { theme, toggleTheme }
}

0 comments on commit dfa9330

Please sign in to comment.
You can’t perform that action at this time.