const getRequests = async () => {
try {
const myHeaders = new Headers();
myHeaders.append("Content-Type", "application/json");
myHeaders.append("token", token);
const response = await fetch(`http://localhost:8081/dashboard/getrequests/${id}`, {
method: "GET",
headers: myHeaders
});
const parseRes = await response.json()
const filterPending = parseRes.filter(x => x.status === 'pending')
const filterConfirmed = parseRes.filter(x => x.status === 'confirmed')
setRequests(await filterPending)
setPassengers(await filterConfirmed)
console.log(filterPending)
} catch (error) {
console.log(error.message)
}
};
const requestsPressHandler = async() => {
await getRequests();
if(requests.length !== 0) {
setIsVisibleRequests(true);
} else {
Alert.alert("You do not have any requests for this lift")
}
};
const passengersPressHandler = async() => {
await getRequests();
if(passengers.length !== 0) {
setIsVisiblePassengers(true);
} else {
Alert.alert("You do not have any passengers for this lift")
}
}
<Button title="requests" onPress={requestsPressHandler} />
The error I am getting is '[Unhandled promise rejection: TypeError: undefined is not an object (evaluating 'requests.length')]'
This error is thrown on the first press of the button, on second press everything executes as it should and no error is thrown (filterPending is saved to state)
Console.log(filterPending) in the getRequests function executes properly on the first press of the button.
Could someone please explain why this is not saving to state on first press of the button?
*** SOLUTION ***
const getRequests = async () => {
try {
const myHeaders = new Headers();
myHeaders.append("Content-Type", "application/json");
myHeaders.append("token", token);
const response = await fetch(`http://localhost:8081/dashboard/getrequests/${id}`, {
method: "GET",
headers: myHeaders
});
const parseRes = await response.json()
const filterPending = parseRes.filter(x => x.status === 'pending')
if (filterPending.length !== 0) {
setRequests(filterPending);
setIsVisibleRequests(true);
setIsVisiblePassengers(false);
}
else {
Alert.alert("You do not have any requests for this lift")
}
} catch (error) {
console.log(error.message)
}
};
const getPassengers = async () => {
try {
const myHeaders = new Headers();
myHeaders.append("Content-Type", "application/json");
myHeaders.append("token", token);
const response = await fetch(`http://localhost:8081/dashboard/getrequests/${id}`, {
method: "GET",
headers: myHeaders
});
const parseRes = await response.json()
const filterConfirmed = parseRes.filter(x => x.status === 'confirmed')
if (filterConfirmed.length !== 0) {
setPassengers(filterConfirmed);
setIsVisibleRequests(false);
setIsVisiblePassengers(true);
}
else {
Alert.alert("You do not have any passengers for this lift")
}
} catch (error) {
console.log(error.message)
}
};
I restructured the function and split it into two, which is referenced directly in the onPress of the button.