简体   繁体   中英

How can I render the components after useEffect hook is finished?

I'm fetching data from an api, and I have a hook which stores the data. I want to render the components after the useEffect hook has fetched data and the data has been set to the data hook. How can I do it?

edit: I need the data before rendering the components.

export const App = () => {
  const [data, setData]

  useEffect(() => {
  axios.get("/data").then((res) => setData(res.data)).catch((err) => console.log(err))
  }, [])

  return (
    <div>
      <Home />
    </div>
  )
}

You can do like as below

export const App = () => {
  const [data, setData] = useState(null);

  useEffect(() => {
  axios.get("/data").then((res) => setData(res.data)).catch((err) => console.log(err))
  }, [])

  return (
    <div>
      <Home setData={setData}/> //here you can pass data to the home component and play with the data
    </div>
  )
}

You can conditionally render a component based on a state. That way it only exists when the state is not null.

export const App = () => {
  const [data, setData] = useState(null);

  useEffect(() => {
  axios.get("/data").then((res) => setData(res.data)).catch((err) => console.log(err))
  }, [])

  return (
    <div>
      {data ? <Home setData={setData}/> : null } // here you can pass data to the home component
    </div>
  )
}

You can add an if statement before the render to check if your data has not been loaded into the state yet, so, you can return null if you do not want the component to render.

export const App = () => {
  const [data, setData] = useState(null)

  useEffect(() => {
    axios.get("/data")
      .then((response) => setData(response.data))
      .catch((error) => console.log(error))
  }, [])

  if (data === null) return null

  return (
    <div>
      <Home />
    </div>
  )
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM