Issue
In useEffect, how can I check each array item has the same vrn and a completed date, so I can navigate them to a different screen:
useEffect(() => {
const isComplete = (completedOn) => completedOn !== '';
if (maintenanceReminder.checkHistory.every(isComplete)) {
navigation.navigate(AppRoutes.MaintenanceIntroVehicleSuccess.Name);
}
}, []);
completed state:
[
{
"id": "Tyres",
"vrn": "WU71JWE",
"completedOn": "2023-10-31T10:20:25.217Z"
},
{
"id": "Wipers and Screenwash",
"vrn": "WU71JWE",
"completedOn": "2023-10-31T10:20:54.743Z"
},
{
"id": "Exterior lights",
"vrn": "WU71JWE",
"completedOn": "2023-10-31T10:21:27.140Z"
}
]
Solution
You would need something in the dependency array to check when the maintenanceReminder
has changed.
Some people say that maintenanceReminder
is sufficient but you would get many re-runs from the useEffect
if maintenanceReminder
is simply a defined variable
i.e. not coming from state:
const [maintenanceReminder, setMaintenanceReminder] = useState([]);
if maintenanceReminder.checkHistory
is simply being created from a variable, then JSON.stringify(maintenanceReminder.checkHistory)
may be sufficient because checking a string
will result in fewer rerunsby the useEffect
becuase a "complex" (JSON or Array) object will cause the useEffect
to run many more times that you would want because of the way React checks the dependencies Docs
useEffect(() => {
if (maintenanceReminder.checkHistory.length === 3 && SOME_OTHER_CHECK) {
navigation.navigate(AppRoutes.MaintenanceIntroVehicleSuccess.Name);
}
}, [JSON.stringify(maintenanceReminder)]);
I've included SOME_OTHER_CHECK
because you mention that you want to check that the "vrn"
is all the same and there is a completed date.
VRN Check
You could check that all the VRN are the same for every item in the array
const firstVRN = maintenanceReminder.checkHistory.length > 0
? maintenanceReminder.checkHistory[0].vrn
: "";
maintenanceReminder.checkHistory.every(item =>
item.vrn === firstVRN
);
Complettion date check
I'd need to more information about the types of possible values for completion date. But you could do something similar that checks that every date is valid.
const isDateValid(dateStr) {
return !isNaN(new Date(dateStr));
}
...
maintenanceReminder.checkHistory.every(item =>
isDateValid(checkDateIsValitem.completedOn)
);
NOTE: I assumed that maintenanceReminder.checkHistory.length === 3
is just a temporary check at the moment as you want to check the VRN and completed dates
Answered By - Harrison
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.