I have read about React hooks and wanted to try it on this new website I have been developing. I am trying to pass an async function as a prop. Part of the function is to set my "cities" state and console log just to see if the API works. I have been receiving "setCities is not a function" error or, cities returns undefined if I just console log it directly. I think the function can't access the {cities, setCities}
state. I have tried it in class component and it works. Has anyone encountered similar situations? Below is the code sample:
import React, { useState } from "react";
import axios from "axios";
import Menu from "./Menu";
function App() {
const { cities, setCities } = useState([]);
const searchSubmit = async term => {
try {
const res = await axios.get("http://localhost:8080/general/search", {
params: { city: term }
});
setCities(res.data);
console.log(cities);
} catch (err) {
console.log(err.message);
}
};
return (
<div className="ui container">
<Menu handleSearchSubmit={searchSubmit} />
</div>
);
}
useStates
return an array, not an object...
So you can change
const { cities, setCities } = useState([]);
to
const [ cities, setCities ] = useState([]);
And it should work.
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.