Quantcast
Channel: Active questions tagged react-native+typescript - Stack Overflow
Viewing all articles
Browse latest Browse all 6211

How to fetch data from a fake server in react native?

$
0
0

I have made a fake server in my laptop to fetch data. this is the data in it:

[  {"id": 1,"firstName": "Bill","lastName": "Gates","email": "bill@microsoft.com","phone": "1234567898","role": "Accountant","org": "Organization 1"  }, {"id": 2,"firstName": "Mark","lastName": "Zuckerberg","email": "mark@facebook.com","phone": "9876543212","role": "Admin","org": "Organization 1"  }]

I run the server using npm run mock:api

I want to fetch data from it and display in my physical android device(phone). This is my code I tried:

constructor(props) {    super(props);    this.state = {        users_fake: []    }}componentDidMount() {    fetch("https://192.168.43.164:4000/users")    .then(response => response.json())    .then((responseJson)=> {        console.log('Response = '+ responseJson);        this.setState({            loading: false,            users_fake: responseJson        })    })    .catch(error=>console.log(error))

and this:

  fetch("http://localhost:4000/users")        .then(response => response.json())        .then((responseJson)=> {        this.setState({        loading: false,        users_fake: responseJson        })        })        .catch(error=>console.log(error))

and this:

 fetch('http://localhost:4000/users', {            method: 'GET'         })         .then((response) => response.json())         .then((responseJson) => {            console.log(responseJson);            this.setState({               users_fake: responseJson            })         })         .catch((error) => {            console.error(error);         });}

I display data like this:

 { this.state.users_fake.map((user, index) => {      return (<Text>{user.firstName} {user.lastName}</Text>     ) })}

But I get error in console:

WARN  Possible Unhandled Promise Rejection (id: 16):TypeError: Network request failed

What should I do to fetch data and display it?


Viewing all articles
Browse latest Browse all 6211

Trending Articles