简体   繁体   中英

How to use useState inside a react functional component which is async

My App is a functional component which is declared async because I have to fetch data from the server before view is rendered and the code is as follows

import React,{useState} from  "react";
import DashBoard from './components/DashBoard'
const axios = require('axios')


const App = async props => {
  const allDashBoardsList = await axios.get('http://localhost:9000/getAllDashBoardNames')
  const [dashboard,setDashboard] = useState(allDashBoardsList.data[0].dashboard)
  const handleDashboardChange = e => {
    setDashboard(e.target.value)
  }
   return (
    <>
      <select>
        {allDashBoardsList.data.map(e => <option value={e.dashboard} onChange  = {handleDashboardChange} > {e.dashboard} </option>)}
      </select>
      <DashBoard dashboard={dashboard} />
    </>
   )
 }



export default App

and my index.js is like this,

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import * as serviceWorker from './serviceWorker';
App().then(e => {
    ReactDOM.render(e, document.getElementById('root'));
})

Everything works fine without any error when i return just <h1> Hello </h1> from App but I am getting

Unhandled Rejection (Error): Invalid hook call. Hooks can only be called inside of the body of a function component

when I use useState to set the state

is there any way to counter this or should I have to use a class component with UNSAFE_componentWillMount

Try wrapping your async call in the useEffect hook instead and setting an acceptable default state

const App = props => {
  const [dashboard,setDashboard] = useState('placeholder default state');

  useEffect(() => {
    const fetchData = async () => {
      const result = await axios.get('http://localhost:9000/getAllDashBoardNames');
      setDashboard(allDashBoardsList.data[0].dashboard);
    };
    fetchData();
  }, []);

  const handleDashboardChange = e => {
    setDashboard(e.target.value)
  }
   return (
    <>
      <select>
        {allDashBoardsList.data.map(e => <option value={e.dashboard} onChange  = {handleDashboardChange} > {e.dashboard} </option>)}
      </select>
      <DashBoard dashboard={dashboard} />
    </>
   )
 }

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