-2

I have this response when I log into an api, I just wanted to get the token from this response in react js

{"success":{"token":"eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJhdWQiOiIxIiwianRpIjoiMDM2M2Y4MGZmMjk3OGY1ZDkwMDdiYTEzODExNjA3ZjdiZGRiODMzYTI3NjM4NzI3ZjcwN2FkNGNhNTRjY2IxYjExODM3MzE3NGI0YTY4NDIiLCJpYXQiOjE1OTIyMjM4NDcsIm5iZiI6MTU5MjIyMzg0NywiZXhwIjoxNjIzNzU5ODQ3LCJzdWIiOiI0Iiwic2NvcGVzIjpbXX0.vaGBiVJInnd1Pv5eviSmnsiGzV3pUuieL6AfyIARM__M15yXlisPHXt-JPBAe_MnBCAPbcyhV21TpJ74RbBwpHfyra9gNLx8rimMFe0SKSmavTC4OwTQq1Gy2cOVIguN_0Rl0uu2kIL4GpRHkK0tErrVIgqXvkpTuO9xZ-DkDyDaaN77GJ-zCFce6zI4RuTQUhdNa553sYfpmRylgUMDYjhRJTM80LACeSARdLTg8FUqVwqD4bTfqtCD5NCB0kxZnFclja9aKRNV4GczhwxfXU84kdjiLY3vGNYE7sXFPC7ucX7c-V84RQMkRqzm8yPuqDig9NfNWyHVOKU0AROVoHUdzOU86_5-DfKZpuNtgfgbkD4KyoHhToTlP-txwyjRCCTaJlwd2_rROtRqR0A9yaFAPRcJ9TB__2GefN063t71IePK8C-Hghse5Zn9G3Ce0Pj3OhARCY_7afqfS0EBBIyiEl-wGc69G_LLD-FejymFhTIwQEc83yUAtiW6S0i8Q3z_5nDU2A60r6F8oGACtMOOH_WuRbS_jMN2NVBHl0ulyn4o5x3XripYRSFIZ1jO0qACUy4RaglX6RzBYqQQecfeOUvQEAOJaEKWbSqQG1X99pO9MGrY7cxSePjqUghVGyeCsKzKlGCYJjrCDZvXGOVtQVOlPfLAinyFWTP4yto"}}
Adriaan
  • 17,741
  • 7
  • 42
  • 75
mali naeem
  • 5
  • 1
  • 6
  • Duplicate of: [How can I access and process nested objects, arrays or JSON?](https://stackoverflow.com/q/11922383) – VLAZ Jun 15 '20 at 12:29

1 Answers1

0

By taking your original answer from the API, you can extract the token by destructing the original object:

your token will be stored in the constant "token"

Assuming that "response" is your returned object from the API:

const { token } = response.success
// Do whatever you want with the token

Working demo:

import React from 'react'

export default () => {
    const response = {"success":{"token":"TOKEN HERE"}}
    const { token } = response.success

    console.log('token',token);

    return null
}
CevaComic
  • 2,056
  • 2
  • 6
  • 12
  • how can I save the token value in a variable ?? – mali naeem Jun 15 '20 at 12:31
  • CevaComic nah bro, thats not how things work in react, you can extract a key value from json object like this in simple javascript but not in react my friend – mali naeem Jun 15 '20 at 12:44
  • ES6 is working fine in React. And that's the way to get the token in this case, assuming that "response" is the returning object from the API. If your object has another name... Change it with that one. – CevaComic Jun 15 '20 at 12:48
  • ah ok I got it now what you meant and it worked, thanks man, Cheers! – mali naeem Jun 16 '20 at 07:10