简体   繁体   中英

React Unable to Access Json Resposne from API

In my website on login,i get a confirmation and a token which i need to store and pass as a property throughout all the pages.I am able to receive the token,but i am unable to store the value for the token and store it as a state value.

Here is the code i have tried so far.

import React from 'react'
import ReactDOM from 'react-dom'
import {Login_Submit_style,Login_button_style,Login_text_field_style,
password_style,para_login_style} from './style'

import Supers from 'superagent'

class Login extends React.Component
{
  constructor(props)
  {
    super(props);
    this.state={username:'',password:''}
    this.Login_data_password=this.Login_data_password.bind(this)
    this.Login_data_username=this.Login_data_username.bind(this)
    this.MainRedirect=this.MainRedirect.bind(this)
    this.api_call_login=this.api_call_login.bind(this)
  }

Login_data_username(e)
{
  this.setState({username:e.target.value})
}

Login_data_password(password)
{
  this.setState({password:password.target.value})
}

MainRedirect()
{
  window.location = '/main';
}

api_call_login()
{
  Supers.post('http://127.0.0.1:8000/user_ops/user_login/')
  .send({'username':this.state.username,'password':this.state.password})
  .then(response => response.json())
  .then(responseData=>{
    console.log(responseData);
  })
    }



render()
{
  return(
    <div style={{background:'yellow'}}>
      <div>
        <h1 style={{marginLeft:550}}>Login Page</h1>
        <div>
          <p style={para_login_style}><b>Username</b></p>
          <input type="text" style={Login_text_field_style} onChange={this.Login_data_username}/>
          <h2>{this.state.username}</h2>
        </div>
        <div>
          <p style={para_login_style} ><b>Password</b></p>
          <input type="password" style={password_style} onChange={this.Login_data_password}/>
        </div>
        <div>
          <button style = {Login_Submit_style} onClick={this.api_call_login}> Log in </button>
        </div>
      </div>
    </div>
  )
}
}

This is the Format in which i get the response: {"Successful_Login": "True", "token": "d278f30445aa0c37f274389551b4faafee50c1f2"}

So ideally i would like to store the values for both the keys returned from the json output.Adn when i use response.body,i am able to get the data in the above format.

I don't know if this will be helpful to you, but I'll try.

Things like XHR calls from a browser to an API are done asynchronously. What you get back is a promise that will execute a function you give it when the call to the API is completed. Your code rightly has a callback function.

However, I don't think that callback function can call setState, because I think (I might be wrong) React wouldn't like it.

I use Redux for React as a way of storing stuff that the rest of the app can just grab when it needs it. Better still, Redux is integrated into React in such a way that whenever this central database is updated, any component that pulls in a piece of data from it (via props) gets updated (re-rendered) automatically.

I think I should point you to the documentation for Redux for more information. There are alternatives to Redux, too.

Good luck, and ask more questions if you get stuck.

In order to set a new state with the values from a json response, I ideally call this.setState right in your promise response.

api_call_login()
{
  Supers.post('http://127.0.0.1:8000/user_ops/user_login/')
  .send({'username':this.state.username,'password':this.state.password})
  .then(response => response.json())
  .then(responseData=>{
    this.setState({ 
      Successful_Login: responseData.Successful_Login,
      token: responseData.token
  })
}

state will be updated when response arrives.

If possible try to use lowercase or camelCase to your keys.

It would be great if you could post link where we can see what exactly is going on, but the way I understand this you would have to add .set('Accept', 'application/json') in your request to get correct json. So, your code should be like:

Supers.post('http://127.0.0.1:8000/user_ops/user_login/')
      .send({'username':this.state.username,'password':this.state.password})
      .set('Accept', 'application/json')
      .then(response => response.json())
      .then(responseData=>{
            console.log(responseData);
})

Since I cannot test, you would have to look if it works. Alternatively, I would suggest you to try using superagent

Let me know if it helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM