Search code examples
javascriptreactjsuse-effect

React text state doesnt update immediately


i am trying to update the text and show the month, the calander updates but the month doesnt update untill i click the next month button twice, but if i click the next month button twice the month is also changed twice in the calander and it shows the previous month on the header.

This is The March month

enter image description here

This is April Month but the month shown is March.

enter image description here

this is my Code

const [showmonth, setShowMonth] = useState(moment().format("MMMM-YYYY"));
const [dateValue, setDateValue] = useState(moment());

const increaseMonth = () => {
    setDateValue(moment(dateValue).add(1, "M"));
    onDateChange(dateValue);
  };
   function onDateChange(value) {
    setShowMonth(value.format("MMMM-YYYY"));
  }
<RightOutlined
                  style={{
                    fontSize: "23px",
                    fontWeight: "700",
                    cursor: "pointer",
                  }}
                  onClick={increaseMonth}
                />

Please Help i am a beginner


Solution

  • Instead of making separate states for your date object and the current month, why not just keep the dateValue as the only state and get the month from that.

    const [dateValue, setDateValue] = useState(moment());
    
    const increaseMonth = () => {
        setDateValue(moment(dateValue).add(1, "M"));
    };
    

    Then, you can have the value of your month be

    dateValue.format("MMMM-YYYY")
    

    This has less code and you only have to update the date object and then your month will update when the days update.