Search code examples
mysqlreactjsselectmultiple-select

How to handle data in react from mysql and also with changing a input select values?


I have this react form which gets prepopulated from mysql. It's a comma delimited field and it loads on the page correctly from the database values. My problem is that when you select another value it's no longer a comma delimited string but an array. I'm just not sure how to handle both data formats. Here's my react code...

  const updateFieldHandler = (key, convert) => e => {
    setSubmissionData({
      ...submissionData,
      [key]: convert ? convert(e.target.value) : e.target.value
    });
    };
    ...
      <FormControl fullWidth className={classes.selectFormControl}>
        <label
          htmlFor="simple-select"
          className={classes.selectLabel}
        >What do you want?{" "}
        </label>
        <Select
          MenuProps={{
            className: classes.selectMenu
          }}
          classes={{
            select: classes.chrisHelp
          }}
          multiple
          input={<Input  />}          
          renderValue={selected => selected.join(", ")}
          onChange={updateFieldHandler("issue_description")}
          inputProps={{
            name: "issue_description",
            id: "issue_description",
            value: submissionData?.issue_description?.split(",").map((description) => {return description}) || []
          }}
        >

Once I add a selection manually I get this error....

_submissionData$issue.split is not a function

on this line...

value: submissionData?.issue_description?.split(",").map((description) => {return description}) || []

Solution

  • So I was able to test for strings and undefined then treated anything else as an array. Now it loads great from db and onchange.

        <Select
          MenuProps={{
            className: classes.selectMenu
          }}
          classes={{
            select: classes.chrisHelp
          }}
          multiple
          required={true}
          input={<Input  />} 
          renderValue={selected => selected.join(", ") }
          onChange={updateFieldHandler("issue_description")}
          inputProps={{
            name: "issue_description",
            id: "issue_description",
            value: (typeof submissionData?.issue_description === 'string' || submissionData?.issue_description instanceof String) ? submissionData?.issue_description?.split(",").map((description) => {return description}) || [] : (typeof submissionData?.issue_description !== 'undefined') ? submissionData?.issue_description || [] : []
          }}
        >