Closed Jzheng213 closed 2 years ago
function handleNextClick() {
if (user.username) {
setInputAns("");
setToggleLikeFav(false);
setNewJoke();
setToggleFetch(!toggleFetch);
setToggleMathProb(!toggleMathProb);
setAnsMsg(null);
diffLevel();
} else {
history.push("/login");
}
}
//state for joke list
const [joke, setJoke] = useState({});
const [allJokes, setAllJokes] = useState([]);
//generate new joke in front end w/o API call
const setNewJoke = () => {
const randomNum = Math.floor(Math.random() * allJokes.length);
const randomJokeObj = allJokes[randomNum];
setJoke(randomJokeObj);
setLikesCount(randomJokeObj.likes);
};
useEffect(() => {
generateMathProb();
fetch("/api/jokes")
.then((res) => res.json())
.then((allJokes) => {
//sets initial random joke
setAllJokes(allJokes);
//sets entire joke list
// const randomNum = Math.floor(Math.random() * allJokes.length);
// const randomJokeObj = allJokes[randomNum];
// setJoke(randomJokeObj);
// setLikesCount(randomJokeObj.likes);
});
setTogglePL(false);
}, [toggleFetch]);
Minor issue - The initial "joke" state (first joke) will not be rendered due to asynchronous rendering. Joke rendering works accordingly after hitting refresh. Any suggestions for fix?
Fixed it, thanks for the suggestion!
What I am suggesting is set the state of the joke to the existing list and make the fetch call in the background or have a useEffect in place of setNewJoke if you want to have it trigger on a state change