I'm trying to display a different colour depending on the amount of days between 2 dates. I've successfully got my differences between the two dates to work, but i'm struggling with updating the colour as it doesn't update straight away as my 'diff' doesn't update. Should I be doing this in a different way? I've tried using the useEffect hook to try and sequence them but its given me errors.
import { useEffect, useState } from "react"
const ColourDisplay = ({ date }) => {
const [colour, setColour] = useState("green")
const [plantDate, setPlantDate] = useState(new Date(date))
const [diff, setDiff] = useState(0)
let colourPicker = () => {
if (diff <= 0) {
setColour('red')
} else if (diff > 0 && diff <= 2) {
setColour('orange')
} else {
setColour('green')
}
}
let diffCalculator = () => {
const today = new Date()
const _MS_PER_DAY = 1000 * 60 * 60 * 24;
const utc1 = Date.UTC(plantDate.getFullYear(), plantDate.getMonth(), plantDate.getDate());
const utc2 = Date.UTC(today.getFullYear(), today.getMonth(), today.getDate());
setDiff(Math.floor((utc1 - utc2) / _MS_PER_DAY))
}
useEffect(() => {
setPlantDate(new Date(date))
diffCalculator(colourPicker)
}, [date])
if (date) {
return <div style={{ backgroundColor: `${colour}` }}>color</div>
}
}
export default ColourDisplay
If anyone can help me out with what i'm doing wrong here then that would be amazing. Thanks all.
CodePudding user response:
I have updated the code
You have used several useless states, one state is enough to show the result.
import { useEffect, useState } from "react";
import * as React from "react";
const ColourDisplay = ({ date }) => {
const [colour, setColour] = useState("green");
let colourPicker = (diff) => {
if (diff <= 0) {
setColour("red");
} else if (diff > 0 && diff <= 2) {
setColour("orange");
} else {
setColour("green");
}
};
let diffCalculator = (plantDate) => {
const today = new Date();
const _MS_PER_DAY = 1000 * 60 * 60 * 24;
const utc1 = Date.UTC(
plantDate.getFullYear(),
plantDate.getMonth(),
plantDate.getDate()
);
const utc2 = Date.UTC(
today.getFullYear(),
today.getMonth(),
today.getDate()
);
colourPicker(Math.floor((utc1 - utc2) / _MS_PER_DAY));
};
useEffect(() => {
diffCalculator(new Date(date));
}, [date]);
if (date) {
return <div style={{ backgroundColor: `${colour}` }}>color</div>;
}
};
export default ColourDisplay;