0

I want to assign a JSON object to a state in react native.

this.state = {
  card: null
}

_getCardDetails() {
  getItem('userData').then(data => {
    this.setState({
      card: data.user.creditCard
    })
  })
}

render() {
  const { card } = this.state
  return (
    <Text>{card}</Text>
  )
}

i'm getting the JSON object from a axios call to my backend. But I can't assign that object to state in React Native.

Response from _getItem()

{
    "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyIjp7ImlkIjo4MzY5NDc5ODk5fSwiaWF0IjoxNTgwMzU1NjkyfQ._tYykbMtegpl58Poat0w2PsMUpnGFypqFd_7P2s6wQ8",
    "next": true,
    "user": {
        "isProfileComplete": false,
        "createdAt": "2020-01-28T11:42:53.413Z",
        "_id": "5e302aa091741b14c0ef18bc",
        "phone": 8369479899,
        "creditCard": {
            "createdAt": "2020-01-28T11:42:53.440Z",
            "creditCardExpiry": "2021-01-28T11:42:53.440Z",
            "_id": "5e302aa091741b14c0ef18bb",
            "creditCardNo": 512723298971919,
            "creditCardCVV": 381,
            "__v": 0
        },
        "__v": 0
    }
}
9
  • Your code looks correct, although incomplete. Please provide the data returned from getItem, and the rest of the component. Commented Jan 30, 2020 at 4:45
  • @FMCorz please have a look at the response Commented Jan 30, 2020 at 4:53
  • The property card.number does not exist. Commented Jan 30, 2020 at 5:02
  • sorry my bad but just card is also not working, I'm getting null only Commented Jan 30, 2020 at 5:04
  • Your code is still incomplete Commented Jan 30, 2020 at 5:06

2 Answers 2

1

Try this,

 this.state = {
      cardDetails: null,
    }


    _getCardDetails() {
      getItem('userData').then(data => {
        this.setState({
          cardDetails: data.user.creditCard
        })
      })
    }

    render() {
  const { cardDetails } = this.state
  return (
    <Text>{cardDetails.creditCardNo}</Text>
  )
}

hope this helps.

Sign up to request clarification or add additional context in comments.

2 Comments

So, by changing the variable name would do the trick? Can you explain why it should work?
you are assigning object to state called cardDetails, but when extracting in text it doesnt take object, there you render card.creditcardnumber thats it
0

Thanks guys, but I found a solution, it is assigning the object but I've to re-render the DOM or page whatever.

So this line helped me {card && this.state.card.creditCardNo}

i'm checking if there's anything in card state

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.