S
S
student9852022-02-02 11:05:15
React
student985, 2022-02-02 11:05:15

Why is React waiting for data to load?

useFetch.js

export const useFetch = () => {
  const [loading, setLoading] = useState(true)
  const [data, setData] = useState([])
  const getProducts = async () => {
    const response = await fetch(url)
    const data = await response.json();
    setData(paginate(data));
    setLoading(false);
  };
 useEffect(() => {
    getProducts()
  }, [])
  return { loading, data }
}


utils.js
const paginate = (followers) => {

    const itemsPerPage = 9;
    const pages = Math.ceil(followers.length / itemsPerPage) ;
    return  Array.from({length:pages}, (_, index) => {
        const start = index * itemsPerPage;
        return followers.slice(start, start + itemsPerPage)
    });

}

export default paginate


app.js
import paginate from "./utils";
function App() {
  const {loading, data} = useFetch();
  const [page, setPage] = useState(0);
  const [followers, setFollowers] = useState([]);
useEffect(()=>{
    if(loading) return;
    setFollowers(data[page])
},[loading])


Can you please tell me why React in this case waits until loading is over? It would seem that he saw that loading = true, exited useEffect and crashed with an error that there was no data. useEffect fires when loading changes, but why doesn't the program continue until loading becomes false?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
@
@insighter, 2022-02-02
@student985

const {loading, data} = useFetch();

loading itself won't change, the App will never be notified that the data has loaded
Pass something like an onLoad callback to your hook

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question