React native connect to laravel passport api and receive access token - reactjs

I set up the backend with Laravel and passport and everything goes correctly when I use postman but when I use Axios in React native app it gives me an error and doesn't load any response
React code:
import React , { Component } from 'react';
import {View , Text} from 'react-native';
import axios from 'axios';
class Lapi extends Component {
state = {
url: 'http://laravelinstallation/api/user'
};
componentWillMount(){
this.getUserInfo();
}
render(){
return(
<View>
<Text>Test</Text>
</View>
);
};
getUserInfo(){
axios.get(this.state.url)
.then(response =>
console.log(response.data)
)
.catch(err =>
console.log(err)
)
}
}
export default Lapi;

Use your IP-address: http://192.168.x.x/laravelinstallation/public/api/user
You can get it by running ipconfig (Windows) or ifconfig (Mac/Linux)

Related

Getting "TypeError: this.state.users.map is not a function" for deployed React application only

Built a web application using React to pull user information from a Firestore database. When running the application locally, it runs flawless and I can load the users information. After deploying it, I now receive a "TypeError: this.state.users.map is not a function" message and the page won't even load. Why would it work in work before deploying it and what would be the fix?
import React, { Component } from 'react';
import AllCoaches from '../components/search/AllCoaches';
import Banner from '../components/layout/banner';
import axios from 'axios';
// MUI Stuff
import Grid from '#material-ui/core/Grid';
import CircularProgress from '#material-ui/core/CircularProgress';
class coaches extends Component {
state = {
users: []
}
componentDidMount() {
axios.get('/coaches')
.then(res => {
console.log(res.data)
this.setState({
users: res.data
})
})
.catch(err => console.log(err));
}
render() {
let coaches = this.state.users ? (
this.state.users.map((user) => <AllCoaches user={user}/>)
) : ( <CircularProgress/> );
return (
<Grid container>
<Banner/>
{coaches}
</Grid>
);
}
}
export default coaches

React app keeps sending multiple request on its own

I'm new to react and I'm trying to build a Weather App for my project. It keeps sending the request to the API I'm using which is OpenWeatherMap API.
I'm using Axios to send the request.
Here's what my code looks like:
import React, {useEffect, useState} from 'react';
import axios from 'axios';
const App = () => {
const [ data, setData ] = useState(null);
const APIKEY = <APIKEY>;
useEffect(()=>{
window.navigator.geolocation.getCurrentPosition(
async position=>{
await axios.get(`https://api.openweathermap.org/data/2.5/onecall?lat=${position.coords.latitude}&lon=${position.coords.longitude}&appid=${APIKEY}`)
.then(response=>{
setData(response.data);
}).catch(error=>{
console.log(error);
})
}
)
}, []);
console.log(data);
return<div>hello</div>
}
export default App;
I tried using class components it doesn't work either way.

Error in Firebase cloud messaging in React PWA

I am trying to add FCM into my Reactjs PWA, but I am unable to resolve the below error
This a very basic app that fetches some data from firebase and shows it on screen.
firebase-messaging-sw.js:
importScripts('https://www.gstatic.com/firebasejs/4.8.1/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/4.8.1/firebase-messaging.js')
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register(`../firebase-messaging-sw.js`)
.then(function(registration) {
console.log('Registration successful, scope is:', registration.scope);
}).catch(function(err) {
console.log('Service worker registration failed, error:', err);
});
}
firebase.initializeApp({
messagingSenderId: SENDER_ID,
})
const initMessaging = firebase.messaging()
App.js:
import React from 'react';
import './App.css';
import Routing from './Components/Routing';
import { BrowserRouter } from 'react-router-dom';
import fire from './config/fire';
function App() {
React.useEffect(() => {
const msg=fire.messaging();
msg.requestPermission().then(()=>{
return msg.getToken();
}).then((data)=>{
console.warn("token",data)
})
})
return (
<BrowserRouter basename={process.env.PUBLIC_URL}>
<div className="App">
<Routing />
</div>
</BrowserRouter>
);
}
export default App;
I have a guess that this is happening because it cannot find any file on the link http://localhost:3000/firebase-messaging-sw.js therefore by default of react-router it is returning the index.html file.

Fetch data from GET request

When I call my API via my web browser I get the following result:
{"statusCode": 200, "body": "\"Cheers from AWS Lambda!\""}
However, I am now struggeling to show body via axios. Do you see what I am doing wrong?
import axios from "axios";
import React, { Component } from "react";
class App extends Component {
state = {
messages: []
};
componentDidMount() {
axios
.get(
"https://12345.execute-api.eu-central-1.amazonaws.com/prod/get-data"
)
.then(response => {
const messages = response.data;
this.setState({ messages });
});
}
render() {
return (
<ul>
{this.messages}
Test
{this.state.messages.map(message => (
<li>{message}</li>
))}
</ul>
);
}
}
export default App;
A few points:
1) Change this.messages in ul of render method to this.state.messages, as this.messages is undefined.
2) A good practice while using JSX is to keep js and html code as distinguishable as possible, so the map on a list should be done outside the return statement.
const listItems = numbers.map((number) =>
<li>{number}</li>
);
return (
<ul>{listItems}</ul>
);
3) For more info about CORS error and how to rectify it while using AWS lambda, refer to this article which includes a code snippet: AWS: CORS

Failed call to Deezer API with React and axios

I want to connect to Deezer API and read data, the API is available here, if you take first links they have there and open in a new tab you will see the data in json, however Axios can't return it
import React from "react";
import ReactDOM from "react-dom";
import axios from "axios";
import "./styles.css";
class App extends React.Component {
componentDidMount() {
axios.get("https://api.deezer.com/album/302127")
.then(response => {
console.log(response);
})
.catch(err => {
console.log(err);
});
}
render() {
return (
<div className="App">
<h2>Deezer</h2>
</div>
);
}
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
Deezer api don't allow cross-origin request. So an api call from browser is not possible.
However you can use a workaround and use https://cors-anywhere.herokuapp.com
You need to change your code like following:
axios.get("https://cors-anywhere.herokuapp.com/https://api.deezer.com/album/302127")
.then(response => {
this.setState({ response })
})
.catch(err => {
console.log('error', err);
});
Here is a working example: https://stackblitz.com/edit/react-v6bufu
However, I will recommend to code your own backend where you will call
Deezer's APIs. You won't be getting cross-origin error there.

Resources