I can't see where the error is here. Why is my useEffect
not accepting the ´yourTheme`value?
Code:
import React, { createContext, useState, useEffect } from 'react';
import { ThemeProvider } from '@material-ui/styles';
import allThemes from './index';
const ThemeContext = createContext({});
const lastThemeIndex = allThemes.length - 1;
const ThemeContextProvider = props => {
const [theme, setTheme] = useState();
const [themeName, setThemeName] = useState(allThemes[0].name);
useEffect(() => {
const yourTheme = localStorage.getItem('theme');
if (yourTheme) {
const themeIndex = allThemes.findIndex(t => t.name === yourTheme);
const selectedTheme = allThemes[themeIndex];
setTheme(selectedTheme);
} else {
setTheme(allThemes[0].theme);
}
}, [yourTheme]);
const setThemeType = () => {
const themeIndex = allThemes.findIndex(t => t.name === themeName);
const nextTheme = allThemes[themeIndex === lastThemeIndex ? 0 : themeIndex + 1];
setTheme({ ...nextTheme.theme });
setThemeName(nextTheme.name);
persistThemeType(nextTheme.name);
};
function persistThemeType(name) {
localStorage.setItem('theme', name);
}
return (
<ThemeContext.Provider
value={{
themeName,
setThemeType,
}}
>
<ThemeProvider theme={theme}>{props.children}</ThemeProvider>
</ThemeContext.Provider>
);
};
export default ThemeContext;
export { ThemeContextProvider };
Image:
You've added yourTheme
into dependency array which is defined inside useEffect
This should cause undefined error. As far as you're getting the value from localstorage, you can remove yourTheme
from dependency array to remove the error.
useEffect(() => {
// ...
}, []);