Skip to content
Advertisement

Refresh data through a new GET request – React Dropdown

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

  const [loading, setLoading] = useState(true);
  const [prepData, setPrepData] = useState([]);
  const [day, setDay] = React.useState(3);

  console.log(day);

  
  const options=["J+1","J+2","J+3", "J+4"]
  
  const handleChange = (event) => {
    setDay(event.target.value);
  };

  useEffect(() => {
    const fetchData = async () => {
      setLoading(true);

      try {
        const {data: response} = await axios.get('/api/home?day=' + day)
        setPrepData(response)
      } catch (err) {
        console.log(err.message)
      }
      setLoading(false)
    }
    
    fetchData()
  }, []);

My dropdown menu :

      <Box key={'box' + index} sx={{ minWidth: 120 }}>
        <FormControl key={'form' + index} fullWidth>
          <InputLabel key={'input' + index} id="dropdown">Date Liv.</InputLabel>
          <Select
            key={'select' + index}
            labelId="select-label"
            id="dateLiv"
            value={day}
            label="Date Liv."
            onChange={handleChange}
            type='submit'
          >
          {(options).map((option, index) => (
            <MenuItem key={'menuItem' + index} value={index + 1}>{option}</MenuItem>
          ))}
          </Select>
        </FormControl>
      </Box>

Advertisement

Answer

You can add day as dependency in useEffect. So that when day value is changed, automatically useEffect will be executed.

useEffect(() => {
    const fetchData = async () => {
      setLoading(true);

      try {
        const {data: response} = await axios.get('/api/home?day=' + day)
        setPrepData(response)
      } catch (err) {
        console.log(err.message)
      }
      setLoading(false)
    }
    
    fetchData()
  }, [day]);   // added day as dependent property
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement