The code should return list of album objects in the console, but is not returning it and instead getting a 500 internal server error.
Error : enter image description here
import React, { Component } from 'react';
import { Text, View } from 'react-native';
import axios from 'axios';
class AlbumList extends Component {
componentWillMount() {
axios.get('https://rallycoding.herokuapp.com/api/music_albums')
.then(function(response){
console.log(response);
})
}
render(){
return(
<View>
<Text> Albums ! </Text>
</View>
);
}
}
export default AlbumList;
can u try this,
axios({
method: 'get',
url: 'https://rallycoding.herokuapp.com/api/music_albums',
}).then(response => {
console.log(response.data);
})
.catch((error) => {
console.log(error);
});
If API return 500 it means error on server side. Not on React-native or front-end Side
I was watching the exact same course and had this problem. As you can see if you read through the questions there, it appears that React Native has some compatibility issues with axios.
My problem was fixed by doing this:
componentWillMount() {
fetch("https://rallycoding.herokuapp.com/api/music_albums")
.then(response => response.json())
.then(data => console.log(data));
}
Related
I currently have this React component that is going to list bottles of alcohol. I'm running into an issue where, although my components state gets returned, I am still not able to map over it.
import React, { Component } from "react";
import Table from 'react-bootstrap/Table'
import Layout from '../../components/layout'
import axios from 'axios';
import {
BrowserRouter as Router,
Switch,
Route,
Link
} from "react-router-dom";
export default class Bottles extends Component {
constructor(props) {
super(props)
this.state = { bottles: [] }
}
componentDidMount() {
axios.get(`http://localhost:3000/api/v1/bottles`)
.then(res => {
const bottles = res.data;
this.setState({ bottles });
})
.catch(function (error) {
console.log(error);
})
}
render() {
return (
<Layout css={{ padding: 0 }} pageTitle="Bottles">
<ul>
{ console.log(this.state.bottles) }
{ this.state.bottles.map(bottle => <li>{bottle.id}</li>)}
</ul>
</Layout>
)
}
}
I have a console log in the render and it seems to render two different items. My guess is the state before the axios request is completed, maybe? But i'm not sure how to correct for this.
If I inspect my console I see two things being output...
[]
{data: Array(20)}
Can anybody help me figure out what is going on here? Little confused here.
It looks like your API is not returning an array as you may have expected, but an object, the one you see in the console. So just change:
const bottles = res.data; to const bottles = res.data.data; and it should work.
Since you are getting {data: Array(20)} in logging this.state.bottles, that means you are looping over an object instead of an array.
In componentDidMount you need to set res.data.data instead of res.data, something like,
axios.get(`http://localhost:3000/api/v1/bottles`)
.then(res => {
const bottles = res.data.data;
this.setState({ bottles });
})
.catch(function (error) {
console.log(error);
})
I hope this resolves the issue.
I'm having trouble getting anything after an axios post to execute. The data posts to the backend as expected, but I can't get anything to run afterwards. Even a console.log after the post doesn't work. I've tried promise and async await based axios and I can't get anything after the post via axios to run. Any ideas what I'm doing wrong?
Create React App 3.3.0
React 16.11
React Router 5.1.2
import React, { Component } from 'react'
import { withRouter } from 'react-router'
import axios from 'axios'
...
class Contact extends Component {
...
submitContactHandler = async event => {
event.preventDefault()
try {
await axios.post('/mail/contact', {
userName: this.state.formData.name.value,
userEmail: this.state.formData.email.value,
userMessage: this.state.formData.message.value
})
this.props.history.push('/about')
console.log("This doesn't even run")
} catch (error) {
console.log(error)
}
}
render() {
...
return (
...
<Form onSubmit = {(event) => this.submitContactHandler(event)}>
...
</Form >
...
)
}
}
export default withRouter(Contact)
Handle the response from backend
await axios.post('/mail/contact', {
userName: this.state.formData.name.value,
userEmail: this.state.formData.email.value,
userMessage: this.state.formData.message.value
})
.then((response) => {
this.props.history.push('/about')
}, (error) => {
console.log(error);
});
I am trying to integrate Active Directory ADAL plugin within my Reactjs app but I am getting error 401 (Unauthorized) when fetching results.
I was following React ADAL package steps till I found a SO question which helped me a lot, but still I am getting a CORS error while fetching Dynamics CRM data.
When I click on the protected route I am redirected to https://login.microsoftonline.com/<someid>/oauth2/authorize?response_type=id_token&client_id=... and then I am redirected back to the page.
This is part of my MyComponent component:
import React, { Component } from 'react';
import { adalApiFetch } from '../../../adalConfig';
class MyComponent extends Component {
constructor(props) {
super(props);
this.state = { APIResponse: '' };
this.getLeads = this.getLeads.bind(this);
}
componentDidMount() {
this.getLeads();
}
getLeads() {
let result;
adalApiFetch(fetch, 'https://myorg.api.crm.dynamics/api/', options)
.then(response => response.json())
.then(data => {
this.setState(Object.assign(this.state, { APIResponse: data }));
console.log(data);
}).catch(error => console.error('SERVER ERROR:', error));
}
render() {
return (
<div>
<h2>My Component</h2>
</div>
);
}
}
export default MyComponent;
I am getting this 401 (Unauthorized) error on the DevTools:
Server error:
SERVER ERROR: SyntaxError: Unexpected end of JSON input
Edit 1:
This is my adalConfig.js code:
import { AuthenticationContext, adalFetch, withAdalLogin } from 'react-adal';
export const adalConfig = {
tenant: 'tenantid',
clientId: 'apiid',
endpoints: {
api: 'apiid'
},
cacheLocation: 'localStorage',
};
export const authContext = new AuthenticationContext(adalConfig);
export const adalApiFetch = (fetch, url, options) => adalFetch(authContext, adalConfig.endpoints.api, fetch, url, options);
export const withAdalLoginApi = withAdalLogin(authContext, adalConfig.endpoints.api);
Any ideas on what is wrong here? Thanks in advance.
I want to display the contents of this api in the console but it isn't working.
What am I doing wrong and how can I fix it?
error I'm getting:
Error: Request failed with status code 401
Here's my code:
import React, { Component } from 'react';
import axios from 'axios';
class Flights extends Component {
constructor(props) {
super(props);
}
componentDidMount() {
axios.get('https://jsonplaceholder.typicode.com/posts')
.then(response => {
console.log("API Call ====> " + response);
}).catch(error => {
console.log(error);
})
}
render() {
return(
<div></div>
);
}
}
export default Flights;
You could use the JSON.stringify() method to parse the response content into a string before printing.
This is the demo: https://codesandbox.io/s/m4nq5lrxxp
An alternative is directly printing it:
axios
.get("https://jsonplaceholder.typicode.com/posts")
.then(response => {
console.log(response.data); // like this without string concatenation
})
.catch(error => {
console.log(error);
});
So this is index.js (my entry point) and I'm loading the json data here
import React from 'react';
import ReactDOM from 'react-dom';
import fetch from 'isomorphic-fetch';
import {Filter} from './src/filter';
fetch('./pizza.json')
.then(function(response) {
return response.json()
}).then(function(json) {
console.log('parsed json', json)
}).catch(function(ex) {
console.log('parsing failed', ex)
});
ReactDOM.render(<Filter />, document.querySelector('.content'));
Now in filter.js where I want to render the contents of the page, I'm not sure how to use the loaded data in index.js, here in filter.js
import React, {Component} from 'react';
export class Filter extends Component {
render() {
return (
<div>
<h1> Pizza Search App </h1>
</div>
);
}
}
I'm new at React.js and am trying to learn, having trouble understand basic react.js fundamentals, help!
You should do the fetching in Filter
import React, { Component } from 'react';
import fetch from 'isomorphic-fetch';
export class Filter extends Component {
state = {
data: null
}
componentWillMount() {
fetch('./pizza.json')
.then(function (response) {
return response.json()
}).then(function (json) {
console.log('parsed json', json)
this.setState(() => ({ data: json }))
}).catch(function (ex) {
console.log('parsing failed', ex)
});
}
render() {
const { data } = this.state
if(!data){
return <div>Loading...</div>
}
return (
<div>
<h1> Pizza Search App </h1>
(use data here...)
</div>
);
}
}
Alex is correct except you need to set the state once you've got the response:
EDIT: I missed that he had another link in his promise chain down there... either way, you only need the one. Like so:
componentWillMount() {
fetch(...).then(res => this.setState({data: res.json()})).catch(....
Also, you need to 'stringify' the json in order to display it in the render method of your component. You're not able to display raw objects like that. Sooo... you'll need to do something like
...
render() {
const { data } = this.state
return (
<div>
<pre>
<code>
{JSON.stringify(data, null, 2)} // you should also look into mapping this into some kind of display component
</code>
</pre>
</div>
)
}