0

I have a select form from MaterialUI that is populated with choices that I received via an axios GET request. This works, however, I now need to axios POST request the selected option in my handleChange(event) function. The data I need to POST from the select drop down should be the string value of the MenuItem, not an index or key.

const useStyles = makeStyles(theme => ({
  root: {
    display: 'flex',
    flexWrap: 'wrap',
  },
  formControl: {
    margin: theme.spacing(1),
    minWidth: 250,
  },
  selectEmpty: {
    marginTop: theme.spacing(1),
  },
}));

function SimpleSelect() {
  const classes = useStyles();
  const [values, setValues] = React.useState({
    firm: '',
    infosys: '',
    spot: '',
  });
  const [choices, setChoices] = React.useState([])

  const inputLabel = React.useRef(null);
  const [labelWidth, setLabelWidth] = React.useState(100)

  useEffect(() => {
    const fetchData = async () => {
      const result = await axios.get(
        'http://127.0.0.1:5000/form/',
      );
      console.log('RESULT DATA: ', result.data)
      setChoices(result.data)
    };
    fetchData();
  }, []);

useEffect(() => {
  console.log(values);
}, [values]);

Below is the area where the issue likely is:

  function handleChange(event) {
    setValues({
      firm: event.target.value
    })
  }

  const selectOptions = choices.map((choice, index) =>
    <MenuItem key={index} value={choice} primarytext={choice}>{choice} 
    </MenuItem>
  ) 

  return (
    <form className={classes.root} autoComplete="off">

      <FormControl className={classes.formControl}>
        <InputLabel htmlFor="firm-helper">Firm</InputLabel>
        <Select
          value={values.firm}
          onChange={handleChange}
          input={<Input name="firm" id="firm-helper" />}
        >
          {selectOptions}  
        </Select>
        <FormHelperText>Select a Firm</FormHelperText>
      </FormControl>
    <form>
  )

I expect to be able to axios POST request in my handleChange function whenever the selected option in the drop down menu changes. I wish to POST the firm value in my values dictionary

Current Output:

Access to XMLHttpRequest at 'http://127.0.0.1:5000/form/' from origin 'http://localhost:3000' has been blocked by CORS policy: Request header field content-type is not allowed by Access-Control-Allow-Headers in preflight response.
xhr.js:166 POST http://127.0.0.1:5000/form/ net::ERR_FAILED
Alex
  • 486
  • 1
  • 7
  • 19

1 Answers1

0

At the point you're using console.log, values will still be the old (current) value. You'll need to use useEffect to execute some kind of effect based on values changing. If you remove your current console logging and add this, you should see a better result. Note: passing the array with values in as the second argument is what tells this effect to happen whenever values changes.

useEffect(() => {
  console.log(values);
  const fetchData = async () => {
    const result = await axios.post(url, { values: values });
  };
  fetchData(); 
}, [values]);
Nick
  • 16,066
  • 3
  • 16
  • 32
  • thank you this makes sense I will update., however, I am still stuck with how to axios POST the selected value. – Alex Aug 13 '19 at 02:01
  • I updated my answer to show how you might do a post request using axios from within `useEffect`! – Nick Aug 13 '19 at 02:07
  • Thank you! this works! However, I am now getting a different error even though the post is being made. I have updated with the new output. – Alex Aug 13 '19 at 02:43
  • Well now you'll have to google `CORS`! Basically, you have to configure your back-end to accept requests from your front-end. – Nick Aug 13 '19 at 02:49
  • haha I am very close! I do have it setup in the backend, but am unsure if the issue is actually there or in the front end. – Alex Aug 13 '19 at 02:54
  • Ah, I didn't read your error close enough: `Request header field content-type is not allowed by Access-Control-Allow-Headers in preflight response.`. Check this answer: https://stackoverflow.com/questions/25727306/request-header-field-access-control-allow-headers-is-not-allowed-by-access-contr – Nick Aug 13 '19 at 02:57