I am trying to restructure the code

I need to move some of the repetitive code into another component the input fields are repetitive need an idea of how can I restructure this code.

import React, { useState, useEffect } from "react";


const apiEndpoint = `${BASE_URL}/form`;
const Form = () => {
  const [sale, setSale] = useState("");
  const [district, setDistrict] = useState("");
  const [billing, setBilling] = useState("");
  const [customer, setCustomer] = useState("");

  const [product, setProduct] = useState("");
  const [prodgroup, setProdgroup] = useState("");
  const [avgprice, setAvgprice] = useState("");
  const [missed, setMissed] = useState("");
  const [qty, setQty] = useState("");
  const [target, setTarget] = useState("");
  const [action, setAction] = useState("");
  const [increment, setIncrement] = useState("");
  const history = useHistory();

  const handleSubmit = () => {
    
     axios
      .post(apiEndpoint, {
       sale,
       district,
       billing,
       customer,
        product,
        prodgroup,
        avgprice,
         missed,
       qty,
         target,
        action,
         increment,
       })
      .then(() => {});
    setSale("");
    setDistrict("");
    setProdgroup("");
    setProduct("");
    setAvgprice("");
    setBilling("");
    setCustomer("");
    setQty("");
    setMissed("");
    setTarget("");
    setAction("");
    setIncrement("");
    history.push("/getForm");
    console.log("ays", sale);
  };

  const { search } = useLocation();
  const urlParams = Object.fromEntries([...new URLSearchParams(search)]);

  useEffect(() => {
    // console.log("arik");
    const {
      salesoff,
      salesdist,
      custname,
      product,
      productgroup,
      billingdoc,
      qtysold,
      avgunitprice,
      targetprice,
      missedopp,
    } = urlParams;
    setSale(salesoff);
    setDistrict(salesdist);
    setCustomer(custname);
    setProduct(product);
    setProdgroup(productgroup);
    setBilling(billingdoc);
    setQty(qtysold);
    setAvgprice(avgunitprice);
    setTarget(targetprice);
    setMissed(missedopp);
    console.log(urlParams);
  }, []);

  const classes = useStyles();

  return (
    <div>
      <Grid container direction="column" alignItems="center" justify="center">
        <Grid item xs={12} lg={6}>
          <Card
            className="p-4 mb-4"
            style={{
              height: 765,
              transform: "rotateX(15deg)",
            }}
          >
            <Container component="main" fixed>
              <CssBaseline />
              <div className={classes.paper}>
                <Logo />

                <div
                  className="heading"
                  style={{
                    marginTop: -73,
                    fontSize: 38,
                    marginRight: 15,
                    color: "#002699",
                  }}
                >
                  <h5>Action Tracker</h5>
                </div>
                <form
                  className={classes.form}
                  noValidate
                  onSubmit={(e) => {
                    e.preventDefault();
                    e.target.reset();
                  }}
                >
                  <Grid container spacing={4}>
                    <Grid item xs={12} sm={6}>
                      <TextField
                        type="text"
                        variant="outlined"
                        fullWidth
                        label="Sales office"
                        onChange={(event) => {
                          setSale(event.target.value);
                        }}
                        value={sale}
                      />
                    </Grid>
                    <Grid item xs={12} sm={6}>
                      <TextField
                        type="text"
                        variant="outlined"
                        fullWidth
                        label="Billing document"
                        onChange={(event) => {
                          setBilling(event.target.value);
                        }}
                        value={billing}
                      />
                    </Grid>
                    <Grid item xs={12} sm={6}>
                      <TextField
                        variant="outlined"
                        type="text"
                        fullWidth
                        label="Sales district"
                        onChange={(event) => {
                          setDistrict(event.target.value);
                        }}
                        value={district}
                      />
                    </Grid>
                    <Grid item xs={12} sm={6}>
                      <TextField
                        variant="outlined"
                        type="number"
                        fullWidth
                        label="Quantity sold"
                        onChange={(event) => {
                          setQty(event.target.value);
                        }}
                        value={qty}
                      />
                    </Grid>
                    <Grid item xs={12} sm={6}>
                      <TextField
                        variant="outlined"
                        fullWidth
                        label="Customer name"
                        onChange={(event) => {
                          setCustomer(event.target.value);
                        }}
                        value={customer}
                      />
                    </Grid>
                    <Grid item xs={12} sm={6}>
                      <TextField
                        variant="outlined"
                        fullWidth
                        label="Avg unit price"
                        onChange={(event) => {
                          setAvgprice(event.target.value);
                        }}
                        value={avgprice}
                      />
                    </Grid>
                    <Grid item xs={12} sm={6}>
                      <TextField
                        variant="outlined"
                        type="text"
                        fullWidth
                        label="Product group"
                        onChange={(event) => {
                          setProdgroup(event.target.value);
                        }}
                        value={prodgroup}
                      />
                    </Grid>
                    <Grid item xs={12} sm={6}>
                      <TextField
                        variant="outlined"
                        type="number"
                        fullWidth
                        label="Target price"
                        onChange={(event) => {
                          setTarget(event.target.value);
                        }}
                        value={target}
                      />
                    </Grid>
                    <Grid item xs={12} sm={6}>
                      <TextField
                        variant="outlined"
                        type="text"
                        fullWidth
                        label="Product name"
                        onChange={(event) => {
                          setProduct(event.target.value);
                        }}
                        value={product}
                      />
                    </Grid>
                    <Grid item xs={12} sm={6}>
                      <TextField
                        variant="outlined"
                        type="number"
                        fullWidth
                        label="Missed opportunity"
                        onChange={(event) => {
                          setMissed(event.target.value);
                        }}
                        value={missed}
                      />
                    </Grid>
                    <Grid item xs={12} sm={6}>
                      <TextField
                        fullWidth
                        value={action}
                        select
                        label={
                          <Typography style={{ fontSize: 17 }}>
                            Action expected
                          </Typography>
                        }
                        variant="outlined"
                        onChange={(event) => {
                          setAction(event.target.value);
                        }}
                      >
                        {actions.map((option) => (
                          <MenuItem key={option.value} value={option.value}>
                            {option.label}
                          </MenuItem>
                        ))}
                      </TextField>
                    </Grid>
                    <Grid item xs={12} sm={6}>
                      <TextField
                        variant="outlined"
                        type="number"
                        fullWidth
                        label="Price increment"
                        onChange={(event) => {
                          setIncrement(event.target.value);
                        }}
                      />
                    </Grid>
                  </Grid>
                  <Button
                    type="submit"
                    fullWidth
                    variant="contained"
                    color="primary"
                    className={classes.submit}
                    onClick={() => handleSubmit()}
                  >
                    Submit
                  </Button>
                  <Grid container justify="flex-end">
                    <Grid item></Grid>
                  </Grid>
                </form>
              </div>
            </Container>
          </Card>
        </Grid>
      </Grid>
    </div>
  );
};

export default Form;

Hello there,

As you have mentioned, I would refactor everything within the form to be an array of objects you can map over. I would have something like:

const MyTextFields = [
  {
    label: "Sales office",
    handleChangeFunction: (e) => {setSale(e.target.value)},
    val: sale
  },
];

Also, what is the point of the .then on your POST request?

Hope this is useful

1 Like

so in a return statement, I am passing this way but doesn’t work for me let me know I am doing correct or not

return object.map((item, index) => {
    <div>
      <TextField
        key={index.key}
        name={item.name}
        value={item.sale}
        onChange={(e) => {
          handleChange(e, item);
        }}
      />
      <TextField
        name={item.name}
        value={item.sale}
        onChange={(e) => {
          handleChange(e, item);
        }}
      />
    </div>;
  });

This won’t work because when mapping over you don’t return anything.

array.map((item) => (
  <div>
    ...
  </div>
));

or

array.map((item) => {
  return (
    <div>
      ...
    </div>
  );
});
1 Like

Thanks for correcting.