I'm trying to pull data from a database and compare the values from the database to the user logged in. The code I'm using to check this looks like:
const [records, setRecords] = useState([]);
const [email, SetEmail] = useState([]);
// This method fetches the records from the database.
useEffect(() => {
async function getRecords() {
const response = await fetch(`http://localhost:5000/admin/`);
if (!response.ok) {
const message = `An error occurred: ${response.statusText}`;
window.alert(message);
return;
}
const admin = await response.json();
setRecords(admin);
let emailList = [];
admin.forEach((x) => {
emailList.push(x.email);
return emailList;
}, SetEmail(emailList));
}
getRecords();
return () => {
};
}, []);
console.log(email);
console.log(email.includes("[email protected]"));
The problem with this is console.log(email) returns multiple empty arrays before returning the fully appended one making it so that if I compare the the current logged in email to the email in the database I get - false, false.. true. Making my component unrederable.
CodePudding user response:
I needed to use the map() function instead
CodePudding user response:
Since you are converting 1 array to another with the same number of entries you can use a map.
Treat console.log as side effects as well and place them inside of useEffects
const [records, setRecords] = useState([]);
const [email, SetEmail] = useState([]);
// This method fetches the records from the database.
useEffect(() => {
async function getRecords() {
const response = await fetch(`http://localhost:5000/admin/`);
if (!response.ok) {
const message = `An error occurred: ${response.statusText}`;
window.alert(message);
return;
}
const admin = await response.json();
const emailList = admin.map(x => x.email);
setRecords(admin);
SetEmail(emailList));
}
getRecords();
return () => {
};
}, []);
useEffect(() => {
console.log(email);
console.log(email.includes("[email protected]"));
},[email]);
