I am trying to fetch data from an API from an input. After providing the input and calling the data, I am getting two fetch call from same data. here is the code of input:
const [countryName, setCountryName] = useState<string>("");
const handleInputChange = (event: {
target: { value: React.SetStateAction<string> };
}) => {
setCountryName(event.target.value);
};
const onSubmit = () => {
navigate(`/country/${countryName}`);
};
<TextField
variant="standard"
placeholder="Enter country Name"
value={countryName}
onChange={handleInputChange}
/>
Here I am using the input to fetch the data:
const { name } = useParams();
const [loading, setLoading] = useState<boolean>(false);
const [country, setCountry] = useState<InitCountry>();
useEffect(() => {
const getCountry = async () => {
setLoading(true);
const response = await fetch(
`https://restcountries.com/v3.1/name/${name}`
);
const data = await response.json();
console.log(data);
setCountry(data.length > 1 ? data[2] : data[0]);
setLoading(false);
};
getCountry();
}, [name]);
What am I doing wrong here?