'Why does my React app not re-render or display changes on the DOM except I relaod?

import { useEffect, useState } from "react";

function Popular() {
  const [popular, setPopular] = useState([]);

  useEffect(() => {
    getPopular();
  }, []);

  const getPopular = async () => {
    const api = await fetch(
      `https://api.spoonacular.com/recipes/random?apiKey=${process.env.REACT_APP_RECIPE_API_KEY}&number=9`
    );
    const data = await api.json();
    setPopular(data.recipes);
  };

  return (
    <div>
      {popular.map((recipe) => {
        return (
          <div>
            <p>{recipe.title}</p>
          </div>
        );
      })}
    </div>
  );
}

export default Popular;

I am pretty new to React, and I encountered this issue which I have been trying to fix to no avail. The code is a component that is to return a list of recipe title to my app. I am fetching data from an API in the getPopular() function which is set to the setPopular function variable of the useState() method. But when I save my work and return to the browser, the changes does not display. The list does not display, but if I console.log(data.recipes) it displays on the console.

Before now, if I made any change (maybe a text change) the React app renders it without reloading, but now I have to reload the page before I see the change.

Please how do I fix this issue? So that I can see changes without having to reload the page manually.



Solution 1:[1]

Not saying that this is the problem, but getPopular() should not be called after its declaration? By this I mean:

 const getPopular = async () => {
   const api = await fetch( 
    /...
  };

 useEffect(() => {
   getPopular();
  }, []);

Another thing that bugs me is, although JS/React is case sensitive, I really think you should avoid having a const called popular, since your functions is Popular.

Please, let me know if the order did matter for your problem. I will review some react classes soon, if i get another inside, i'll let you know.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Fábio Rengel