Home > database >  Learning react, trying to understand useReducer()
Learning react, trying to understand useReducer()

Time:10-28

I just learned about the useReducer hook and wanted to try to experiment some to see if I could get a better handle on how it works.

I have a very simple app that when a button is clicked, the background changes to the color of the button's label, and the text in the center changes to display the active color.

When the button is clicked, I am able to see the the correct color logged to the console, however, the display text disappears, and the color does not update.

Here is the code snippet:

import "./styles.css";
import { useReducer } from 'react'

const colors = [
  '#2a9d8f',
  '#e9c46a',
  '#e76f51',
]

const reducer = (state, action) => {
  switch (action.type) {
    case 'CHANGE_COLOR':
      return( 
      state = `'${action.payload}'`,
      console.log(state)
      )
    default:
      return state
  }
}

export default function App() {

  const [state, dispatch] = useReducer(reducer, '#ffffff')

  return (
    <div className="App" style={{backgroundColor: state}}>
      {colors.map(color => {
        return (
          <button 
            key={color}
            className='colors' 
            style={{backgroundColor: color}} 
            onClick={() => {dispatch({ type: 'CHANGE_COLOR', payload: color })}}>{color}</button>
        )
      })}
      <span> Color: {state} </span>
    </div>
  );
}

Forgive me, this is probably a super easy fix, but I'm trying to learn, just very, very.... very slowly.

Thanks!

CodePudding user response:

You are on the right track but you made a small mistake in your reducer funtion. The function should return the state value rather than setting the value to the state prop:

const reducer = (state, action) => {
  switch (action.type) {
    case 'CHANGE_COLOR':
      return( 
        // state = `'${action.payload}'`, // WRONG
        `${action.payload}` // CORRECT
      )
    default:
      return state
  }
}

Also I omitted the '' in the returned value to keep it consistent with the initial value.

  • Related