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.
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/
You can do it with string concatenation:
const string = `{ \"class": ${classname}, \"name": ${name}, \"instanceNumber": 0, \"properties": [ \ \] \ }`;
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: []};