I am trying to understand this issue. Why state (country in this case) is not updating setCountry just after execute function only when I click another time? In this example when I choose a country and then click Add Country to state in function addCountry() in first console.log is working good and showing the current chosen country but the second console.log with country state is showing the previous one. Of course when {country} is rendering in return then obviously is showing current situation. So my question what should I use to udpate coutry in the second console.log correctly?
import React, { useState} from "react";
const Country = () => {
const [country, setCountry] = useState([]);
const countries = ["Poland", "England", "Germany", "USA"];
const showCountries = countries.map((country) => <option>{country}</option>);
const addCountry = () => {
const selectCountry = document.getElementById("selectCountry").value;
console.log(selectCountry); //There is current country
setCountry(selectCountry);
console.log(country); //There is previous country
};
return (
<>
<select id="selectCountry">{showCountries}</select>
<button onClick={addCountry}>Add Country</button>
<div>{country}</div>
</>
);
};
export default Country;