Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

      <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>

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading