Question: I am loading data from an API into my functional app component with useEffect (example below). I can't understand how to then set the variable activeToken because phrases is not yet defined, perhaps because useEffect is async?
What pattern should I be using to ensure that phrases exists before I invoke activeToken?
function App() {
const getActiveToken = (tokens) => {
for(let i = 0; i < tokens.length; i++) {
if (tokens[i].mask === true) {
return i
}
}
}
useEffect(() => {
fetch('http://localhost:5000/api/v1')
.then((response) => response.json())
.then((data) => setPhrases(data))
}
)
const [termIndex, setTermIndex] = useState(0);
const [phrases, setPhrases] = useState([]);
const [activeToken, setActiveToken] = useState(getActiveToken(phrases[termIndex].tokens))}