I'm currently trying to show the Location depending on the ID number selected in the dropdown. I currently have a handler that will grab the current selected ID in the dropdown. I just have a couple questions.
https://jsfiddle.net/Yellohh/wq0trdas/30/
const request = axios.create({
baseURL: "https://veselka.maka-ars.com",
timeout: 30000,
});
const endpointIds = "/fiddle/getIds";
function Dropdown() {
const [ids, setIds] = React.useState([]);
const [location, setLocation] = React.useState();
const [value, setValue] = React.useState([]);
React.useEffect(() => {
request.get(endpointIds).then((response) => {
const loadedIds = [];
for (const id of response.data.ids) {
loadedIds.push({ id });
}
setIds(loadedIds);
});
}, []);
/* const endpointLocation = "fiddle/getLocation/" + event.target.value; */
React.useEffect(() => {
request.get(endpointLocation).then((response) => {
const loadedLocation = response.data.location;
setLocation(loadedLocation);
});
}, []);
const valueChangeHandler = (event) => {
setValue(event.target.value);
};
console.log(event.target.value);
const idsList = ids.map((id) => <option>{id.id}</option>);
return (
<div>
<select onChange={valueChangeHandler}>{idsList}</select>
<p>{location}</p>
</div>
);
}
For your second question, you could give the state an initial value. Perhaps a you have an ID in mind?
You can do this via: (in this case -1 is the initial value)
const [location, setLocation] = React.useState(-1);
You can also validate the request parameters before you execute the request, in this case validate it is defined.
For your first question; are the actions part of the same flow? As in does a certain user action always start a flow that should trigger both actions, or can they trigger independently. If yes then in my opinion they can be grouped together.
Another tip, go checkout the array reducer concept. It can make those for loops to extract values more readable.
To answer your first question in order for the request to be sent each time the user value changes add the value as a dependence inside the useEffect.
And about your second question before you send a request make sure you have a value, if you don't just return
React.useEffect(() => {
if (!value) return;
request.get(endpointLocation).then((response) => {
const loadedLocation = response.data.location;
setLocation(loadedLocation);
});
}, [value]);