Reputation: 67
I am new in react native so i don't have any idea how to connect laravel rest api with react native. My first question is that laravel run on http://127.0.0.1:8000 while react native run on my wifi ip address so both run on different host and port , so is there any issue with that or it is fine? secondly how i get data from laravel api , i create something like that in app.js file
class App extends React.Component{
constructor()
{
super();
this.state={
data :[]
}
}
componentDidMount()
{
this.callApi();
}
async callApi()
{
let data=await fetch('http://127.0.0.1:8000/api/users')
let adata= await data.text();
this.setState({data:adata})
console.warn(ddata)
}
render(){
console.warn("render",this.state.data)
return(
<View>
<Text style={{fontSize:50}}>FlatList</Text>
<FlatList
data={this.state.data}
renderItem={({item})=><Text style={{fontSize:50}}>{item.name}</Text>}
keyExtractor={(item, index) => index.toString()}
/>
</View>
)
}
}
export default App;
but this gives me alot of error
Upvotes: 1
Views: 1946
Reputation: 169
If you are on the same wifi network, you have to use your ip instead of localhost:8000
or 127.0.0.1:8000
, like
192.168.1.2:8000
[your_ip]:[port]
Upvotes: 1
Reputation: 88
Both your devices should be on the same network (ie if you're using two devices). In case of emulator, you can use laravel api through localhost in react native project, but in case of an actual mobile phone (if you're using expo), its localhost is different than that of your computer, so there might be a network error. It is better to host the api, (this is what I did) it solves a lot of problems. As for those errors, show them to us.
Upvotes: 1