I have a code similar to below:
const Example = (props) => {
//custom hook that returns a country name selected by user
{ selectedCountry, setSelectedCountry } = useSelectedCountry();
const [country, setCountry] = useState();
const countryList = props.countryList;
return(
<Box>
<label htmlFor='country'>Country</label>
<Select
sx={{ m: 1, width: inputSelectWidth, mt: 3, height: 35, ml: 12 }}
value={country}
onChange={(e) => { setCountry(e.target.value); } }
>
{
countryList.map(country => {
return (
<MenuItem
value={country.countryName}
key={country.countryID}
>
{country.countryName}
</MenuItem>
);
})
}
</Select>
</Box>
);
}
export default Example;
I need the country to change when selectedCountry is changes. But selectedCountry is updated in another component. If I console.log(selectedCountry); in this component it gets updated every time I select different country from the other component.
Although country should change when selectedCountry changes, country can have its own value. For example
selectedCountry: A, country: A
selectedCountry: B, country: B
selectedCountry: B, country: C
selectedCountry: B, country: D
I tried value={selectedCountry} But then value of country and selectedCountry are always same. I need to implement the above scenario.
I don’t know how to do this. Any ideas?
>Solution :
You can use React.useEffect hooks to set up the behaviour you need. The code may look something like that inside your Example component:
React.useEffect(() => {
// This function will be executed each time the `country` is changed
// like in the `Select` component.
}, [country]};
React.useEffect(() => {
// This function will be executed each time the `selectedCountry` is
// changed, probably outside the `Example` component.
}, [selectedCountry]};
React.useEffect(() => {
// This function will be executed each time either `country`
// or `selectedCountry` is changed.
}, [country, selectedCountry]};
Use whatever option you find the best and put the required logic inside the function. And don’t forget to import React or the useEffect hook in the beginning of the file.
More on this and other hooks on React docs: https://reactjs.org/docs/hooks-effect.html.