Alex Khanas
Alex Khanas

Reputation: 345

React hooks, state is not changing correctly

In this project I use react hooks, this snippet used to change color theme of project, but there's the problem which I can not to solve. const lightTheme = { ... }

  const darkTheme = {
     ...
  }
 export const ThemeState = ({children}) => {

  const initialState = {
     theme: lightTheme
  }

  const [state, dispatch] = useReducer(ActionReducer, initialState)

  const {theme} = state 

  const themeToggler = (e) => {
     e.preventDefault()
     console.log(theme)
     if(theme == lightTheme){
        dispatch({type:THEME, payload: darkTheme})
     }
     else if(theme == darkTheme){
        dispatch({type:THEME, payload: lightTheme})
     }
   }

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.

My reducer:

export const ActionReducer = (state, action) => {
         switch(action.type) {
           case THEME:
             return{
               ...state,
               theme: action.payload
            }
           default:
              return state
   }
};

Here is component with toggle button by each click, I need to change theme in state, it clicks correctly: 
import {ThemeContext} from '../../store/themeState'

function Main () {
  const {theme, themeToggler} = useContext(ThemeContext)
   return (
       <button onClick={e => {themeToggler(e)}}></button>
   )
}

 export default Main

 when I press the button i catch this log


    ({body: "#E2E2E2", text: "#363537"}
      {body: "#363537", text: "#FAFAFA"}
      {body: "#363537", text: "#FAFAFA"}
      ....)

I don't know why do state changes like this. If you can, help me to solve this bug.)


Upvotes: 1

Views: 156

Answers (3)

Domino987
Domino987

Reputation: 8804

The initial theme is body: '{#E2E2E2', text: '#363537'}.

When you click the button, you log this theme {body: "#E2E2E2", text: "#363537"}, which is correctly your initial theme.

After you log it, you update the theme to be the dark theme {body: '#363537', text: '#FAFAFA'}.

This will be logged, once you click the button again: {body: "#363537", text: "#FAFAFA"}.

Now comes the problem, since you create the darkTheme object on every render, the references are not the same as previous, so the comparison else if(theme == darkTheme) fails, because the darkTheme object is different from the previous darkTheme object.

Either move the theme object generation out of the component, so you do not generate a new one on every render or add a type to the theme:

const lightTheme = {
  body: '#E2E2E2',
  text: '#363537',
  type: "light"
}`

and compare those: if(theme.type == darkTheme.type)

Upvotes: 4

SuleymanSah
SuleymanSah

Reputation: 17888

What you need is to toggle the theme on button click:

So you can do this:

ThemeState

import React, { useReducer } from "react";
import { TOGGLE_THEME } from "./ActionTypes";
import ActionReducer from "./ActionReducer";

const lightTheme = {
  body: "#E2E2E2",
  text: "#363537"
};

const darkTheme = {
  body: "#363537",
  text: "#FAFAFA"
};

const initialState = {
  isLightTheme: true
};

export const ThemeState = ({ children }) => {
  const [state, dispatch] = useReducer(ActionReducer, initialState);

  const { isLightTheme } = state;

  const themeToggler = e => {
    e.preventDefault();
    dispatch({ type: TOGGLE_THEME });
  };

  const backgroundColor = isLightTheme ? lightTheme.body : darkTheme.body;
  const fontColor = isLightTheme ? lightTheme.text : darkTheme.text;

  return (
    <div style={{ backgroundColor: `${backgroundColor}` }}>
      <p style={{ color: `${fontColor}` }}>Some Text</p>
      <button type="submit" onClick={themeToggler}>
        Toggle Theme
      </button>
      <hr />
      Current Theme: {isLightTheme ? "light" : "dark"}
    </div>
  );
};

ActionReducer:

import { TOGGLE_THEME } from "./ActionTypes";

export default function(state, action) {
  switch (action.type) {
    case TOGGLE_THEME:
      return {
        ...state,
        isLightTheme: !state.isLightTheme
      };
    default:
      return state;
  }
}

ActionTypes:

export const TOGGLE_THEME = "TOGGLE_THEME";

Codesandbox

Upvotes: 1

Neskews
Neskews

Reputation: 824

I created a minimal example on how this behavior could be implemented:

const darkTheme = {
  color: "green"
};

const lightTheme = {
  color: "red"
};

export default function App() {
  const [useLightTheme, setUseLightTheme] = useState(true);

  return (
    <div className={useLightTheme ? darkTheme.color : lightTheme.color}>
      <button onClick={() => setUseLightTheme(!useLightTheme)}>toggle</button>
      some example text
    </div>
  );
}

Since you did not provide all relevant code (e.g. the reducer), I can't explain your code.

Upvotes: 0

Related Questions