Question: I am working on a form in React e-commerce project.

Here's how it should work: When user fills up the form and clicks the submit button I want to post the form data to a server and redirect the user to a confirmation/thank you page.

Unfortunately, when I fill up the form and click the submit button the following code works in a specific way:

1st click - it sends the data but "setSubmitted(true)" doesn't work so I am not redirected

2nd click - is sends the data again, setSubmitted works and I am redirected

Could you tell me how to fix the code?

```
let history = useHistory();
const [submitted, setSubmitted] = useState(false);

const handleSubmit = (e) => {

e.preventDefault();

fetch('http://localhost:8000/orders', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({ cart: 1 }), //dummy data
})
  .then((response) => {
    setSubmitted(true);
    return response.json();
  })
  .then(() => {
    if (submitted) {
      return history.push('/thank-you-page');
    }
  });
};

  return (
  <form onSubmit={handleSubmit}> ... </form>
  );

```

Answer: 
You can loop over each key value pair and replace the value if its empty. Be aware that a backslash is used for escaping a character. To fix this we first replace the backslashes with dashes and then replace the rest.

The regex could also be simplified to `/[^-|]/g` which means replace all symbols except `-` and `|`

```js
const lines = {
    "part": "Intro",
    "e": "------5/6-----8\\6-|-------------------|-------------------",
    "B": "-----------9-------|---------6p8---(6)-|-------------------",
    "G": "--8----------------|---8h9-------------|--<8>--------------",
    "D": "",
    "A": "",
    "E": "",
    "endMsg": "Continue..."
};

const createFullLines = (lines, blacklist = ['part', 'endMsg']) => {
  // Find a line that is not empty
  const line = Object.entries(lines).find(([key, line]) => {
    return !blacklist.includes(key) && line.trim();
  });

  // Exit if all lines are empty
  if(!line) return lines;

  // Destructure to get only value
  const [_, filledLine] = line;

  // Create new line with only dashes
  const newLine = filledLine.replace(/[^-|]/g, '-');

  // Update lines
  for(const key in lines) {
    lines[key] ||= newLine;
  }

  return lines;
}

const result = createFullLines(lines);

console.log(result);
```
You should just iterate between your object's keys like this:

```js
// find first non-empty field, !! - conversion to boolean
let nonEmptyKey = Object.keys(obj).find(key => !!obj[key]);

for(let key of Object.keys(obj)) {
  // check if value is empty
  if(!obj[key]) {
    obj[key] = obj[nonEmptyKey].replace(/[0-9-. a-zA-Z // \ ~ ( ) < >]/g, '-');
  }
}

```

Also, you can simplify your regex to this:

```js
// replace all symbols except - and |
str.replace(/[^-|]/g, '-');

```