There are two points in your code that I believe are important you fix and that will probably solve your problem.
- The function passed to the
useEffect
should not be a function async
, the correct would be:
useEffect(() => {
...
}, [])
you can use the traditional then
and catch
to make asynchronous calls, but in case you want to use async/await
you can do something like this:
useEffect(() => {
async function fetchMyAPI() {
let response = await fetch('api/data')
response = await response.json()
dataSet(response)
}
fetchMyAPI()
}, [])
- the
useEffect
"should" receive a second parameter, this parameter is not mandatory, but in most cases you will want to declare it to avoid unnecessary executions. This second parameter is basically a array
with values that React will be "observing", if any of these values is changed your useEffect will run again, usually values like state or properties passed to the component are added in this array, if they are being used by useEffect. I strongly recommend you take a look at this documentation section: Hooks Reference API - useEffect
In your case you could change your useEffect
leaving him like this:
useEffect(() => {
axios.get('...').then(res => setTrees(res.data)).catch(() => alert("error"))
}, [emailTest])
Another important detail would be to initialize your state so that it maintains the type of data you would like to store, for example, I suppose that trees
be an array of objects, so that you do not have a type error when using the method map
, recommend you change your status statement leaving it that way:
const [trees, setTrees] = useState([])
with this you ensure that your code will not break as long as the call to the api in is finished.