I have this Dropdown Menu (done with MUI) which allows to choose the day value. When it changes, I’d like it to make a new GET request with the new parameter, but I don’t know how to do it as it uses useEffect.
My function to fetch data
JavaScript
x
29
29
1
const [loading, setLoading] = useState(true);
2
const [prepData, setPrepData] = useState([]);
3
const [day, setDay] = React.useState(3);
4
5
console.log(day);
6
7
8
const options=["J+1","J+2","J+3", "J+4"]
9
10
const handleChange = (event) => {
11
setDay(event.target.value);
12
};
13
14
useEffect(() => {
15
const fetchData = async () => {
16
setLoading(true);
17
18
try {
19
const {data: response} = await axios.get('/api/home?day=' + day)
20
setPrepData(response)
21
} catch (err) {
22
console.log(err.message)
23
}
24
setLoading(false)
25
}
26
27
fetchData()
28
}, []);
29
My dropdown menu :
JavaScript
1
19
19
1
<Box key={'box' + index} sx={{ minWidth: 120 }}>
2
<FormControl key={'form' + index} fullWidth>
3
<InputLabel key={'input' + index} id="dropdown">Date Liv.</InputLabel>
4
<Select
5
key={'select' + index}
6
labelId="select-label"
7
id="dateLiv"
8
value={day}
9
label="Date Liv."
10
onChange={handleChange}
11
type='submit'
12
>
13
{(options).map((option, index) => (
14
<MenuItem key={'menuItem' + index} value={index + 1}>{option}</MenuItem>
15
))}
16
</Select>
17
</FormControl>
18
</Box>
19
Advertisement
Answer
You can add day
as dependency in useEffect
. So that when day value is changed, automatically useEffect
will be executed.
JavaScript
1
16
16
1
useEffect(() => {
2
const fetchData = async () => {
3
setLoading(true);
4
5
try {
6
const {data: response} = await axios.get('/api/home?day=' + day)
7
setPrepData(response)
8
} catch (err) {
9
console.log(err.message)
10
}
11
setLoading(false)
12
}
13
14
fetchData()
15
}, [day]); // added day as dependent property
16