Home > Software design >  Working with Strings and useState variables in react js?
Working with Strings and useState variables in react js?

Time:05-10

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.

CodePudding user response:

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/

CodePudding user response:

You can do it with string concatenation:

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

CodePudding user response:

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: []};

CodePudding user response:

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>

CodePudding user response:

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);

  • Related