ama icon indicating copy to clipboard operation
ama copied to clipboard

How to use random data in hooks?

Open liuuu opened this issue 6 years ago • 1 comments

every render will create a new request, so it's bug

import React, {useEffect, useState, useRef} from "react";
import ReactDOM from "react-dom";
import "./styles.css";

function useFetch(url){
  const item = useRef()
  const [data, setData] = useState(null)
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState(null)
  const fetchData = async (url) => {
    try{
      const {data} =await (await fetch(url)).json()
      setData(data)
    }catch(e){
      setError(e)
    }
    setLoading(false)
  }

  useEffect(() => {
      fetchData(url)
 }, [url])


  return {data, loading, error}
}

function App() {
  const id = Math.floor(Math.random() * 10 +  1)
  const endPoint = `https://reqres.in/api/users/${id}`
  const {data, loading, error} = useFetch(endPoint)

  if(data) {
    return <div><img src={data.avatar} /></div>
  }
  if(loading){
    return <div>loading</div>
  }
  if(error){
    return <div>err</div>
  }
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

liuuu avatar Apr 12 '19 13:04 liuuu

What's your question exactly? What are you trying to do?

hedgerh avatar Apr 15 '19 19:04 hedgerh