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

128
Visualizações
why i'm a getting NaN

i tried This pattern of including the dispatch functionality in my reducer function but i got this NaN whatever i try to increment or decrement what's the thing that i'm missing basically creating helper method in my reducer function for better api approach might not be the best approach but at least i tried things differently what's the problem that i'm missing in order for this to work [forgive my english]

import * as React from 'react';

const CounterContext = React.createContext();

function CounterProvider({ step = 1, initialCount = 0, ...props }) {
    const [state, dispatch] = React.useReducer(
        (state, action) => {
            const change = action.step ?? step
            switch (action.type) {
                case 'increment': {
                    return { ...state, count: state.count + change }
                }
                case 'decrement': {
                    return { ...state, count: state.count - change }
                }
                default: {
                    throw new Error(`Unhandled action type:${action.type}`)
                }
            }
        },
        { initialCount: initialCount })
    const increment = React.useCallback(() => dispatch({ type: 'increment' }), [
        dispatch
    ])
    const decrement = React.useCallback(() => dispatch({ type: 'decrement' }), [
        dispatch
    ])

    const value = { increment, decrement, state }
    return <CounterContext.Provider value={value} {...props} />
}

function useCounter() {
    const context = React.useContext(CounterContext)
    if (context === undefined) {
        throw new Error('useCounter must be used within CounterProvider')
    }
    return context
}

function Counter() {
    const { state, increment, decrement } = useCounter();
    console.log(state, 'inc ', increment, 'dec ', decrement)
    return (
        <div>
            <button onClick={decrement}>-</button>
            <button onClick={increment}>+</button>
            <div>Current Count: {state.count}</div>
        </div>
    )
}
function App() {
    return (
        <CounterProvider>
            <Counter />
        </CounterProvider>
    )
}
export default App
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

Because you pass initial value is { initialCount: initialCount }. So you don't have count. Just update to count

{ count: initialCount }
about 4 years ago · Juan Pablo Isaza Relatório

0

It's simple you just have to update your { initialCount: initialCount } to count in order to get the value.

It should look like this { count: initialCount }

about 4 years ago · Juan Pablo Isaza 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