My Experience on completing advice generator project from frontendmentor

My Experience on completing advice generator project from frontendmentor

Fetch API in react

This is one of the project from frontendmentor that generate advice after dice icon is clicked.

This is one my first project which I have completed only using react. Fetching API is one of important things to learn. Even though I have learn from tutorials how to fetch API in react, doing in my first project was quite an experience.

useEffect is one of react hooks that will help use implement fetch. The useEffect Hook allows you to perform side effects in your components and you should use fetch in useEffect because fetching data from an API, communicating with a database, and sending logs to a logging service are all considered side-effects, as it's possible to have a different output for the same input. For example, your request might fail, your database might be unreachable, or your logging service might have reached its quota.

First of all, use useState to store fetch data, error and loading. We will have to update things later.

const [error, setError] = useState(null);
  const [isLoaded, setIsLoaded] = useState(false);
  const [advice, setAdvices] = useState([]);

Now thendeclare useEffect and then inside call the fetch with the url. Store the the data in response and have it return as JSON. Everything was find until that point for me. And also make sure to use empty array as callback.

useEffect(() => {
    fetch(url)
      .then(res => res.json())
      .then(
        (result) => {
          setIsLoaded(true);
          setAdvices(result);
        },
        (error) => {
          setIsLoaded(true);
          setError(error);
        }
      )
  }, []);

The fetch return an JSON as object where I use expecting it to be array. If it was an array I would have use map function to iterate data but it is an object. Now object has to be iterate in another way and that has to be outside JSX. So now I will use for loop to store the data I want from object in variable like below:

let text="";
  let id="";
  for(let x of Object.keys(advice)){
      id+=`${advice[x].id}`;
      text+=`${advice[x].advice}`;
  }

And now I will implement the variable in JSX . This is how I handle fetch API in react. You can check the live project here

Any suggestion for improvement my fetching API in react is welcome!!!