I want setTickets to wait for the getTickets function to get the data… but it doesn’t. i tried using async await and by making setTicket(getSavedTickets()) my function. How can I fix this?
Console logs show everything running before the DB has a chance to respond, at most, 2 seconds later.
import React, { useState, useEffect } from 'react';
import getSavedTickets from './getTickets';
function SubmissionForm () {
const [tickets, setTickets] = useState('')
useEffect (() => {
if (document.cookie.length > 0) {
const myPromise = new Promise((res, rej) => {
res(getSavedTickets());
}).then((response) => {
setTickets(response);
})
}
}, []);
return (
<div>
{!tickets ? [] : tickets.map((tickets) => {
return <li key={tickets.id}>
From: {tickets.afrom} Subject: {tickets.asubject} Body: {tickets.abody}
</li>
})}
</div>
)
}
export default SubmissionForm;
This is the function its importing. I’ve also tried setting this to return a promise but of course it had no effect.
function getSavedTickets() {
if (document.cookie.length > 0) {
fetch(`http://${myIP}:3001/ticketCheck`, {
method: 'POST',
mode: 'cors',
headers: { 'Content-Type': 'application/json',},
body: JSON.stringify({"user": [{username: document.cookie.split('=')[1]}]})
})
.then(response => response.json(),
error => console.log(error),
)
.then(response => {
return response.dbRes;
})
}
}
export default getSavedTickets;
idk what to do. Every time I run into async issues in JavaScript the syntax or functionality makes it an extremely toxic couple of hours.
2
Answers
Looks like it was not waiting because async needed to be added to get saved tickets. using .then instead of await. Fetch returns a promise to the async function needed return next to fetch. That let the async function getSavedTickets return a promise. It fulfilled the .then in the main file with useEffect in it.
Not returning a promise and making the initially function Async was throwing me off. Having those 2 issues to work out instead of one.
getSavedTickets
main file
getSavedTickets is itself a promise, you don’t need to create a new promise in the useEffect, just do something like
edit: looks like getSavedTickets also needs to be updated to return said promise: