DEV Community

loading...

Discussion on: React useEffect() hook tutorial for begginers

Collapse
ratuloss profile image
Ratul Author • Edited

run this code in stackblitz.com sandbox has some bugs in this case

import React, { useEffect, useState } from "react";

const App = () => {
  const [data, setData] = useState("");
  const fetchData = async () => {
    const api = await fetch("https://jsonplaceholder.typicode.com/todos/");
    setData(await api.json());
  };
  console.log(data);
  useEffect(() => {
    fetchData();
  }, [data]);
  return <></>;
};

export default App;

Enter fullscreen mode Exit fullscreen mode
Collapse
onivue profile image
onivue

Hello Ratul

Thank you for the reply.
I Think it does not work well, because it fetch the Data endless...

But i took the time and researched for a solution and here is it:

import React, { useState, useEffect } from "react";

function useFetch(url) {
  const [data, setData] = useState([]);
  const [loading, setLoading] = useState(true);
  async function fetchUrl() {
    const response = await fetch(url);
    const json = await response.json();
    setData(json);
    setLoading(false);
  }
  useEffect(() => {
    if (!loading) {
      console.log(data);
    } else {
      fetchUrl();
    }
  }, [loading]);
  return [data, loading, setLoading];
}

function App() {
  const [data, loading, setLoading] = useFetch(
    "https://jsonplaceholder.typicode.com/todos"
  );

  return (
    <>
      <button onClick={() => setLoading(true)}>Load Data</button>
      <h1>Data</h1>
      {loading ? (
        "Loading..."
      ) : (
        <ul>
          {data.map(({ id, email, userId, title }) => (
            <li key={`id-${id}`}>
              [User_{userId}] - {title}
            </li>
          ))}
        </ul>
      )}
    </>
  );
}
export default App;
Enter fullscreen mode Exit fullscreen mode

thanks to your post I was able to be successful!

Thread Thread
ratuloss profile image
Ratul Author

Nice solution

import React, { useEffect, useState } from "react";

const App = () => {
  const [data, setData] = useState("");
  const fetchData = async () => {
    const api = await fetch("https://jsonplaceholder.typicode.com/todos/");
    setData(await api.json());
  };
  console.log(data);
  useEffect(() => {
    fetchData();
  }, [data]);
  return <>
    <h1>I am fethcing some fake data's</h1>
</>;
};

export default App;
Enter fullscreen mode Exit fullscreen mode

This one also woks fine just put the state as your effect dependencies. So it will fetch the data when the value of our state variable changes.
I have a repo on useEffect fetch api, your can visit that -> github.com/Ratul-oss/github-users-...

:)