1

I have two useStates, which stores the values taken from the user.

const [classname, setClassname] = useState('');
const [name, setName] = useState('');

Similarly I have a string that has to be passed as body for the Rest API post request.

const string = '{ \ "class": "Device", \ "name": "some name", \ "instanceNumber": 0, \ 
                  "properties": [ \ \ ] \ }';

I have to pass the classname in place of device and and name in place of some name in the string. How can I change the string according to the useState values.

5 Answers 5

2

You can use string interpolation for this, it is process of embedding an expression into part of a string:

const string = `{ \ "class":"${classname}", \ "name": "${name}", \ "instanceNumber": 0, \ 
                  "properties": [ \ \ ] \ }`;

Here is a reference to learn more https://dmitripavlutin.com/string-interpolation-in-javascript/

Sign up to request clarification or add additional context in comments.

2 Comments

On posting this I get bad request error.
Updated the answer have a look.
0

Parse the string (JSON) to an object, update the properties, and then stringify it. That way you're left with a clean string that doesn't have those escape backslashes.

const className = 'Android';
const name = 'Max 2.0';

const str = '{ \ "class": "Device", \ "name": "some name", \ "instanceNumber": 0, \ "properties": [ \ \ ] \ }';

const obj = JSON.parse(str);

obj.class = className;
obj.name = name;

const json = JSON.stringify(obj);

console.log(json);

Comments

0

You can do it with string concatenation:

const string = `{ \"class": ${classname}, \"name": ${name}, \"instanceNumber": 0, \"properties": [ \ \] \ }`;

Comments

0
const string = `{ \ "class": ${classname}, \ "name": ${name}, \ "instanceNumber": 0, \ 
                  "properties": [ \ \ ] \ }`;

But if you are sending it to an api as a post request I would recommend sending it as a object as it would be easier to access the values in the backend. As a object:

const string = { class: classname, name: name, instanceNumber: 0, properties: []};

1 Comment

While this code may answer the question, providing additional context regarding why and/or how this code answers the question improves its long-term value.
0

Create an object with the desired properties and then stringify it using JSON.stringify and then send the stringified object with the POST request.

The example below takes two inputs from the user and then sends a stringified object as the body of the POST request.

function App() {
  const [title, setTitle] = React.useState("");
  const [body, setBody] = React.useState("");

  const handleSubmit = (e) => {
    e.preventDefault();

    fetch("https://jsonplaceholder.typicode.com/posts", {
      method: "POST",
      body: JSON.stringify({
        title,
        body,
        userId: 1,
      }),
      headers: {
        "Content-type": "application/json; charset=UTF-8",
      },
    })
      .then((response) => response.json())
      .then((json) => console.log(json));
  };

  return (
    <form onSubmit={handleSubmit}>
      <input placeholder="Title" value={title} onChange={({ target }) => setTitle(target.value)} />
      <input placeholder="Name" value={body} onChange={({ target }) => setBody(target.value)} />
      <button type="submit">Send</button>
    </form>
  );
}

const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>
);
<script crossorigin src="https://unpkg.com/react@18/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@18/umd/react-dom.development.js"></script>
<div id="root"></div>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.