faraz
faraz

Reputation: 337

how to save specific data from json object in new state into react native

Here is my code

 handleLogin = async()=> {
    const { navigation } = this.props;
    const errors = [];

    Keyboard.dismiss();
    this.setState({ loading: true });



     if(this.state.email!=''){
       if(this.state.password!=''){
    fetch('http://192.168.1.10:8000/api/login',{
      method:'post',
      headers:{
        'Content-Type':'application/json',
       'Accept': 'application/json'
      },
      body:JSON.stringify({


            "email":this.state.email,
           "password":this.state.password

      })
    })
    .then((response)=> response.json())
    .then((res)=>{

       var store=JSON.stringify(res) 

      this.setState({ errors, loading: false });
      if(this.state.store==='{"error":"Unauthorised"}'){
        Alert.alert("Error", "These credentials do not match our records");
      }
      else {
          Alert.alert("Success","You have succesfuly login",
          [
        {
          text: 'Continue', onPress: () => {
             Actions.NavigationCalling();
          }
        }
      ],
      { cancelable: false })
      }
    }).catch((error)=>{
      console.error(error);
    });
  }
  else{
    this.setState({ errors, loading: false });
    Alert.alert("Please insert Password")
  }
}
  else{
    this.setState({ errors, loading: false });
    Alert.alert("Please insert email")
  }

var store=JSON.stringify(res)

Im storing data in store variable that print output like this

{"success":{"token":"eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsImp0aSI6Ijk4YjYzNTY4NjNkNmYxNzBhYjdlYjVmNWRiN2MxNWU1NTUzNDc3OWUyZjM5Mjc5NWU4ODMzMjM3NDU1Y2Q3ODg1YzYzZTc0NDg2MmNjYzk2In0.eyJhdWQiOiIxIiwianRpIjoiOThiNjM1Njg2M2Q2ZjE3MGFiN2ViNWY1ZGI3YzE1ZTU1NTM0Nzc5ZTJmMzkyNzk1ZTg4MzMyMzc0NTVjZDc4ODVjNjNlNzQ0ODYyY2NjOTYiLCJpYXQiOjE1ODA5MzA2MzYsIm5iZiI6MTU4MDkzMDYzNiwiZXhwIjoxNjEyNTUzMDM2LCJzdWIiOiIzIiwic2NvcGVzIjpbXX0.A1NZcxICOu8mudwrIrozG5FYiQxWyz1O8LcHFcaOvgXUlTkgUIuGuwxif74goMwCLkWrm3wIwZSKwMAxCAk35Ao9VZEsV3uOlelWtsjJY7u-o00baCUl3dZWJeBHLLfSODM719Oinrfepp5VGaGZ4r--rMqMnNljVEoUP8GuM0l_7rY-SA7dhXkj4a8TwogkZOzf1_0ZvgNYmM30Z_CU0umM72Iqcys-URnzb80HONI4_cVcYExqmU94UqhNsNJ9aMIDXR4WdMGzDBzhRat_E75u7Rbt67UKUbbwALv3J1qhGRb-kkE_DGR3DyAxlcNvMy21CR4b4obDE4e96GYb-7R7fLw0PiVtiyFTgLeL2Ldvw4YV8_v2TwF5zLgkh0VCqfjUTIbAir9ytjDBPDzXFy7G4mAR6qJYNPSHtgwzBcMuS2B4FWZruWg-0QbHiBFFQrDGISaf5jUTSCmiSbpd3eTKAhiifBE6eGNnzErlsG1WAn8L7zK233l1b7qDSoahIrK4PTllgsdEzFtI4sXpy_9mEbRmGmEjOTXZcUyvkFm6aajXrRwWGrhSMFIeFqRd2BNTnrh2Igwl9x7Dcj89VgXKGXyh-hP4ESwT5yHAynNhVfhaXAu1kdnkzhwzk5cDlKlYawvX02g83THN6UAElj2bttIutM-fZ1ViLIOA98k"}}

But i want to store just token in new state and pass to other screen how can i get only token from json object and store into newstate and pass into new screen

Thanks in advance I'm new in the React native

Upvotes: 0

Views: 569

Answers (1)

Abdullah Asendar
Abdullah Asendar

Reputation: 604

You can access the token by doing res.success.token or you can map the json response to an object.

.then((res)=>{
  var token = res.success.token // did you try doing this?
  var store=JSON.stringify(res) 
  this.setState({ errors, loading: false });
  ....

And to pass the token to another screen you can use the screen props or use redux, however, i would set it in a static variable to be accessed globally by all the screens.

I am working on a react native app that does pretty much the same that you are trying to do, i created a class called ApiService that has the following function:

static async post(url: string, payload?: object, headers?: HeadersInit_): Promise<ApiResponse> {
    return await fetch(url, {
        method: "POST",
        headers: headers,
        body: JSON.stringify(payload),
    }).then(r => r.json().then(o => {
        var mapper = new ApiResponse();
        mapper.success = o.success;
        mapper.result = o.success ? JSON.stringify(o.result) : o.error;
        return mapper;
    })).then(response => {
        if (response.success)
            return response;

        throw ApiError(response);
    });
}

The ApiResponse class looks like this:

class ApiResponse {
    public success: boolean;
    public result: string;
}

To access the auth token globally, i am setting the token in a static variable in a class that can be accessed everywhere.

class AbstractService {

    private static sessionToken: string;

    public static setSessionToken(value: string): void {
        AbstractService.sessionToken = value;
    }

    public static getSessionToken(value: string): string {
        return AbstractService.sessionToken;
 }

If you want to store the token to be reused, you can use react-native-secure-key-store

Upvotes: 1

Related Questions