Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting component state to JSON in React

I am new to React JS. I wanted to convert the component state data into a JSON object. Is it possible? If so, how?

Sample state :

this.state = {
    name : "Example",
    age : "21",
    description : "Some text here."
}

That's the whole question. I would appreciate it if you could tell me where I can find simple tutorials to do more advanced things in React (like sending/receiving JSON to/from a server, doing redirects, creating menus, etc). I know I sound vague, and I don't expect very specific answers(if any) to this.

like image 258
Spectrum Avatar asked Dec 19 '17 14:12

Spectrum


People also ask

How do I change the state of component in react?

To update our state, we use this. setState() and pass in an object. This object will get merged with the current state. When the state has been updated, our component re-renders automatically.

How convert data into JSON format in react native?

Just use JSON. stringify method in order to turn an javascript object into JSON text and store that JSON text in a string. Also, you can use JSON. parse which turns a string of JSON text into a Javascript object.

Which method is used to change the component state?

Always use the setState() method to change the state object, since it will ensure that the component knows it's been updated and calls the render() method.


1 Answers

Just use JSON.stringify method in order to turn an javascript object into JSON text and store that JSON text in a string.

Also, you can use JSON.parse which turns a string of JSON text into a Javascript object.

let state = {
    name : "Example",
    age : "21",
    description : "Some text here."
}
console.log(state);
console.log(JSON.stringify(state));
like image 189
Mihai Alexandru-Ionut Avatar answered Oct 22 '22 03:10

Mihai Alexandru-Ionut