jng34 / math-is-a-joke

1 stars 1 forks source link

Fix rendering issue #1

Closed Jzheng213 closed 2 years ago

Jzheng213 commented 2 years ago
useEffect(() => {
    generateMathProb();
    fetch("/api/jokes")
      .then((res) => res.json())
      .then((allJokes) => {
        //sets random joke
        const randomNum = Math.floor(Math.random() * allJokes.length);
        const randomJokeObj = allJokes[randomNum];
        setJoke(randomJokeObj);
        setLikesCount(randomJokeObj.likes);
      });
    setTogglePL(false);
  }, [toggleFetch]);

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

const [setAllJokes, allJokes] = [];
const setNewJoke = () => {
    const randomNum = Math.floor(Math.random() * allJokes.length);
    const randomJokeObj = allJokes[randomNum];
    setJoke(randomJokeObj);
}

useEffect(() => {

    generateMathProb();
    fetch("/api/jokes")
      .then((res) => res.json())
      .then((allJokes) => {
        //sets random joke
        setAllJokes(allJokes);
        setLikesCount(randomJokeObj.likes);
      });
    setTogglePL(false);
  }, [toggleFetch]);
Jzheng213 commented 2 years ago
  function handleNextClick() {
    if (user.username) {
      setInputAns("");
      setToggleLikeFav(false);
      setNewJoke();
      setToggleFetch(!toggleFetch);
      setToggleMathProb(!toggleMathProb);
      setAnsMsg(null);
      diffLevel();
    } else {
      history.push("/login");
    }
  }
jng34 commented 2 years ago
//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?

jng34 commented 2 years ago

Fixed it, thanks for the suggestion!