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

264
Visualizações
cannot update context in react typescript functional component

I'm currently working on using context hook in react typescript and having some trouble with updating and confused about the .Provider and .Comsumer of the API.

this is my code about increasing 1 day when clicking on the button

import React, {createContext, useContext, useState} from "react"


type MonthCalendarProps = {

};


const CalendarContext = createContext({
    focusDate: new Date(),
    selectedDate: new Date(),
    changeFocusDate: (date: Date) => {}
})



function IncreaseButton(props : any) {

    const calendarContext = useContext(CalendarContext)

    const increase = () => {
        console.log(props.value.focusDate)
        let tmpDate : Date = calendarContext.focusDate
        tmpDate.setDate(tmpDate.getDate() + 1)
        calendarContext.changeFocusDate(tmpDate)
    }

    const getStringFromDate = (date: Date) : string  => {
        console.log(date)
        return date.toDateString()
    }

    return (
        <div>
            <p>{getStringFromDate(calendarContext.focusDate)}</p>
            <button onClick = {increase}>
                +
            </button>
        </div>
    )
}

export default function MonthCalendar ( {} : MonthCalendarProps) {

    const [focusDate, setFocusDate] = useState(new Date())
    const [selectedDate, setSelectedDate] = useState(new Date())
    const value = {focusDate: focusDate, selectedDate: selectedDate, changeFocusDate: setFocusDate}

    const context = useContext(CalendarContext)

    console.log(context.focusDate)

    return (
        <CalendarContext.Provider value = {value}>
           <CalendarContext.Consumer>
                {value => <IncreaseButton value = {value}/>}
            </CalendarContext.Consumer>
        </CalendarContext.Provider>
    )
}

When clicking the button, the console.log inside increase function showed that the focusDate is updated but the UI ,a.k.a <p>{getStringFromDate(calendarContext.focusDate}</p> was not updated.

What's the problem with my code and how to fix it? and can you guys explain Why?

If it's possible, can you also explain more about behavior of .Consumer and .Provider for me please?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

let tmpDate : Date = calendarContext.focusDate
tmpDate.setDate(tmpDate.getDate() + 1)
calendarContext.changeFocusDate(tmpDate)

You are mutating the existing date object, not creating a new one. When you set state, react will do an === between the old and new state. Since they're the same object, it looks like nothing has changed, and so react skips rendering.

Instead, make a new date:

let tmpDate = new Date(calendarContext.focusDate);
tmpDate.setDate(tmpDate.getDate() + 1)
calendarContext.changeFocusDate(tmpDate)

P.S, in MonthCalendar you're calling const context = useContext(CalendarContext). This will only get the context from parent components. It will not get the context from itself. That's not contributing to the bug in IncreaseButton, but it will cause the console.log(context.focusDate) to be misleading

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