Rohit K
Rohit K

Reputation: 128

Unable to parse JSON in react for post method

I have a post function where I'm sending a JSON response to the server to change the visibility of an attribute to true/false. The response being sent is in format: { "keywordId":"KW-0604", "visibility": "False" }

My post function is as below and is being called within ComponentWillUpdate()

keyadd(){
     axios.post('http://localhost:8080/visualization/interact/keyword/update', 
    { keywordId: this.state.visible_keywords,  visibility: 'False' })
    .then(function (response) {
      console.log(response);
    })
    .catch(function (error) {
      console.log(error);
    });
   }

For the keywordId I'm passing the json string from this.state.visible_keywords which I get by splicing data between two tables in our dashboard.

this.state.visible_keywords gets the data in format: [{"keywordId":"KW-0604","keywordName":"Branched-acid biosynthesis"}] which is a valid JSON response.

However from the above JSON string I only want to send the keywordID. I tried using JSON.stringfy() and JSON.parse() functions but of no success.

With my given set of post function I know the server will respond with an error response.

I've been trying to find a solution for this but in vain.

Regards,

Upvotes: 1

Views: 233

Answers (2)

Black.Jack
Black.Jack

Reputation: 1959

You could basically do this way :

axios.post('http://localhost:8080/visualization/interact/keyword/update'
        , { keywordId: Object.values(this.state.visible_keywords)[0], visibili‌​ty: 'False'})
      .then(function (response) {
        console.log(response);
      })
      .catch(function (error) {
        console.log(error);
      });

since

this.state.visible_keyword

is already JSON, and parsing is useless.

Notice that if you do something like:

axios.post('http://..yourURL', this.state.visible_keywords)...

is perfectly valid, just confirming what I've said.

Upvotes: 0

simbathesailor
simbathesailor

Reputation: 3687

This should work

{keywordId:this.state.visible_keywords[0].keywordId,visibili‌​ty: 'False'} 

Upvotes: 1

Related Questions