Anu
Anu

Reputation: 1742

How to fetch the response of JSON array in react native?

rq.js

}).then((responseData) =>{
        this.setState({
            user:responseData.name,
            user1:responseData.blood,
            user2:responseData.location,
            loaded: true,
        })

This is my code in react native.It works perfect if my JSON response is not an array.What change do i need to make in this code to work perfectly if json is an array?Showing this error Unexpected token < in JSON at position 1

data.json

[{"name":"hema","bld":"O -ve","lc":"london"}]

this is my json array input.Anybody please help..

Upvotes: 1

Views: 5293

Answers (3)

Aakash Sajjad
Aakash Sajjad

Reputation: 97

I know it's too late, but I hope it's helpful for others. How to fetch the response of JSON array in react native?

export default class ExpenseNew extends Component {
    constructor(){
        super();
        this.state={
            accountnameMain:[],
        }
    }
     componentDidMount(){
         var account_nam=[]
                fetch('your Url', {
                    method: 'GET',
                    headers: { 'Authorization': 'Bearer ' + your token }
                })
                    .then((response) => response.json())
                    .then((customerselect) => {
                        // alert(JSON.stringify(customerselect)) 
                        global.customerdata = JSON.stringify(customerselect)
                        var customername = JSON.parse(customerdata);
                        //alert(JSON.stringify(customername));
                        for (i = 0; i < customername.cus_data.length; i++) {
                            var dataa = customername.cus_data[i]["account_name"];  
                            account_nam.push(dataa)
                        }
                        this.setState({accountnameMain:account_nam});
                    })
                    .done();
    }

account_name is my field/column name, in your case, your column name is bld so you can fetch all data and push in var type of array, then set data in state type of array, and map anywhere you want.

Upvotes: 0

Johan
Johan

Reputation: 329

If You want it work with an array just do

}).then((responseData) =>{
    this.setState({
        user:responseData[0].name,
        user1:responseData[0].blood,
        user2:responseData[0].location,
        loaded: true,
    })

in this way you are calling the first object of the array's index and then the prop of this first object in the array

Upvotes: 1

Johan
Johan

Reputation: 329

try sending the data as a object not as array

{"name":"hema","bld":"O -ve","lc":"london"}

and actually you are calling props blood and location, but your JSON content bld and lc for that props

Upvotes: 1

Related Questions