Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

126
Visualizações
trying to adjust a state object in redux but i can't change the value of one property in the object

Ok so i have this very basic example of redux state

const initialState = {
  good: 0,
  ok: 0,
  bad: 0,
};

const counterReducer = (state = initialState, action) => {
  console.log(action);
  console.log(state);
  console.log(initialState);
  console.log(state.good);

  switch (action.type) {
    case "GOOD":
      return { ...state, good: good + 1 };
    case "OK":
      return { ...state, ok: ok + 1 };
    case "BAD":
      return { ...state, bad: bad + 1 };

    case "ZERO":
      return state;
    default:
      return state;
  }
};

export default counterReducer;

i'm trying to change only one property of the state object on an onclick function named like this

const store = createStore(reducer);

const App = () => {
  const addGood = () => {
    store.dispatch({
      type: "GOOD",
    });
  };
  const addBad = () => {
    store.dispatch({ type: "BAD" });
  };
  const addOk = () => {
    store.dispatch({ type: "OK" });
  };

  return (
    <div>
      <button onClick={addGood}>good</button>
      <button onClick={addOk}>ok</button>
      <button onClick={addBad}>bad</button>
      <button>reset stats</button>
      <div>good {store.getState().good}</div>
      <div>ok {store.getState().ok}</div>
      <div>bad{store.getState().bad}</div>
    </div>
  );
};

const renderApp = () => {
  ReactDOM.render(<App />, document.getElementById("root"));
};

renderApp();
store.subscribe(renderApp);

but when i try to change the value of any of the properties it doesn't work , for example good , ok , bad but it crashes my app if i do so with good is not defined error

about 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

You have to replace good: good + 1 with good: state.good + 1, Likewise for other state, make these changes. state.{property} returns the current value of that property in the state before being updated.

about 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda