Reputation: 777
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
Upvotes: 0
Views: 595
Reputation: 53
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} />
</>
)
}
Upvotes: 2