Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading