React fetch asinchronous data from POST request and display data - reactjs

I am trying to fetch some data from an API through a POST request, then I would like to display those data on the browser, but I am encountering this problem:
Line 30: Expected an assignment or function call and instead saw an expression
My code looks like this:
import React, { Component } from "react";
import axios from "axios";
class GetData extends Component {
componentDidMount() {
axios
.post(
`https://api.multicycles.org/v1?access_token=API_KEY`,
{
query:
"query ($lat: Float!, $lng: Float!) {vehicles(lat: $lat, lng: $lng) {id type attributes lat lng provider { name }}}",
variables: { lat: 52.229675, lng: 21.01223 }
}
)
.then(response => {
console.log(response);
this.setState({
data: response.data
});
})
.catch(error => {
console.error(error);
});
}
render() {
console.log(this.state.data);
return (
<ul className="filter-options">
{this.state.data.data.map(val => {
<p>{val.templateFields}</p>;
})}
</ul>
);
}
}
export default GetData;
I would like then, to render in App.js a component called <GetData /> and display the results from the API, but I'm still getting the error previously mentioned.
Where I'm doing something wrong?

I'm not sure where you're getting
this.state.data.data
from. You're setting
this.setState({
data: response.data
});
so I would expect something like
this.state.data.map(...)
I also don't see a constructor for your component - you need to set default, state, for example
constructor(props) {
super(props);
this.state = {date: new Date()};
}

You're not returning anything in your map try :
<ul className="filter-options">
{this.state.data.data.map(val => (
<p>{val.templateFields}</p>
))}
</ul>
Also you need a default state in your component.

Related

React problems when i try to make an api call using fetch

i have a problem i try to make an api call to https://randomuser.me/api/ using fetch and i try to setstate my value array to the api data and then to map and i cant figure out where is the problem in my code because i get some errors
import "./App.css";
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
value: [],
};
}
componentDidMount() {
fetch("https://randomuser.me/api/")
.then((res) => res.json())
.then((data) => this.setState({ value: data }));
}
render() {
return (
<div>
<p>test</p>
<div className="map">
{this.state.value.map((item) => (
<p>{item.gender}</p>
))}
</div>
</div>
);
}
}
export default App;
The endpoint you are fetching from sends the response as an object, when you try to setState with the call this.setState({ value: data }) it sets the entire response object as this.state.value. That is why you get the error "this.state.value.map is not a function" because this.state.value was replaced as an object by the setState call.
I believe you want the value of results property from the response object which has the correct array data for the user. You can simply change the setState call to set the value as data.results.
componentDidMount() {
fetch("https://randomuser.me/api/")
.then((res) => res.json())
.then((data) => this.setState({ value: data.results }));
}

axios get request in reactJS

I am new to the react and I am learning how to HTTP get request using axios. I am referring to a youtube video: https://www.youtube.com/watch?v=NEYrSUM4Umw and following along, but I got an error. I think I have minor error but I can't figure it out.
import React, { Component } from 'react'
import axios from 'axios'
class PostList extends Component {
constructor(props) {
super(props)
this.state = {
posts: []
}
}
componentDidMount(){
axios.get('https://api.particle.io/v1/devices/64646468431646/temperature?access_token=547376a1b2')
.then(response => {
console.log(response)
this.setState({posts: response.data})
})
.catch(error => {
console.log(error)
}
)
}
render() {
const { posts } = this.state
return (
<div>
temperature
{
posts.length ?
posts.map(post => <div key={post.coreInfo.deviceID}> {post.result} </div>) :
null
}
</div>
)
}
}
export default PostList
When I use postman to get a HTTP request, I get the following response:
{
"cmd": "VarReturn",
"name": "temperature",
"result": "67.55",
"coreInfo": {
"last_app": "",
"last_heard": "2020-04-05",
"connected": true,
"last_handshake_at": "2020-04-05",
"deviceID": "64646468431646",
"product_id": 8
} }
My goal is to display the result: 67.55 in the web application.
Thank you in advance
If you're only getting a single object as the response from your fetch instead of an array, just wrap it in an array -
this.setState({posts: [response.data]})

React doesn't render API data

Im building a recipe App and I got stuck and there is no error display or anything that can help me, Its my first time working with APIS in React and Im a little bit lost thats why im asking.
I´m trying to fetch data from this API and I don´t know why the properties will not show on the screen since I ve another example where it does.
I can see in the console with the React Developer extension that the properties are passed to the state so that´s fine and I dont understand why I cannot access or why it doesnt render.
In the other example doesn't get the data from an API it gets the data from a local object in json. Does it work different when it comes an API? Any idea?
import React, { Component } from "react";
class App extends Component {
constructor(props) {
super(props);
this.state = {
recipes: []
};
}
componentDidMount() {
this.fetchData();
}
fetchData() {
fetch("https://www.themealdb.com/api/json/v1/1/random.php")
.then(response => response.json())
.then(json => {
this.setState({ recipes: json });
})
.catch(error => console.log("parsed error", error));
}
render() {
return <div className="box">{this.state.recipes.strMeal}</div>;
}
}
export default App;
Your code looks okay, but you need to render somehow your backend data:
fetchData() {
fetch("https://www.themealdb.com/api/json/v1/1/random.php")
.then(response => response.json())
.then(json => {
this.setState({ recipes: json.meals });
})
.catch(error => console.log("parsed error", error));
}
render() {
return (
<div className="box">
{this.state.recipes.map(m => <p>{m.strMeal}</p>)}
</div>
);
}
recipes is a json with meals key that is an array. Each element in the array has strMeal key (name of the meal).

Display data from the response returned from axios. Reactjs

Please help me ! i am very new to reactjs
I am able to get response from web service . But i am unable to display the same on screen(mainly have to display in dropdown which i havn't tried yet as first step for me is to see the data on screen).
My webservice data :
[{"id":1,"db_name":"mysql","status":true,"urlRequired":true,"userNameRequired":true,"passwordRequired":true,"dbNameRequired":true}]
My code :-
import React from 'react';
import ReactDOM from 'react-dom';
import axios from 'axios';
class FetchDemo extends React.Component {
constructor(props) {
super(props);
this.state = {
posts: []
};
}
componentDidMount() {
let currentComponent = this;
axios.get(`http://10.11.202.253:8080/ETLTool/getAllDBProfile`)
.then(function (response) {
console.log(response);
console.log(response.data);
currentComponent.setState({
posts: response.data.items
});
})
.catch(function (error) {
console.log(error);
});
}
render() {
const renderItems = this.state.posts.map(function(item, i) {
return <li key={i}>{item.title}</li>
});
return (
<ul className="FetchDemo">
{renderItems}
</ul>
);
}
}
export default FetchDemo;
Error :-enter image description here
My response data via axios :-
enter image description here
I would remove .items since your response won't have that every time and just handle the data your receive in a render function if needed.
You could just do a conditional check when you set your state since I guess your db could be empty at some point:
currentComponent.setState({ posts: response.data ? response.data : [] });
In the above case, the mistake is with understanding Component Lifecycle of React.
Please take a look at the reference.
ComponentDidMount occurs after the render has occurred.
Hierarchy will be
1. constructor
2. componentWillMount
3. render
4. componentDidMount
if the code is modified with
render() {
if (this.state.posts.length) {
let renderItems = this.state.posts.map(function(item, i) {
return <li key={i}>{item.title}</li>
});
}
return (
<ul className="FetchDemo">
{renderItems}
</ul>
);
}
OR
replace ComponentDidMount with ComponentWillMount
componentWillMount() {
let currentComponent = this;
axios.get(`http://10.11.202.253:8080/ETLTool/getAllDBProfile`)
.then(function (response) {
console.log(response);
console.log(response.data);
currentComponent.setState({
posts: response.data.items
});
})
.catch(function (error) {
console.log(error);
});
}
Personal preference is the first suggestion as it checks "posts" state is initialized with Array or not if it's not an Array then map function will surely through an error.
Adding to it, there might be a problem with how you are taking the response from axios too.
currentComponent.setState({
posts: response.data.items
});
as I don't think response.data.items will give any data, as it should be limited to response.data only.
currentComponent.setState({
posts: response.data
});

How do I access data returned from an axios get to display on a web page using react js?

I have ajax functions in an api to which I'm making an axios get request from my react js component. How can I access the returned data to display it on the web page.
Depends of what you trying to do but this is a example.
componentDidMount() {
axios
.get(`endpoint`)
.then(res => this.setState({ posts: res.data }))
.catch(err => console.log(err))
}
A good way too should be if you using react-router to make the ajax call with the onEnter api from the router.
Here is one way of doing it with React and ES2015.
You will want to set the default state in the constructor and make your get request like in the example below. Just switch the names around to make it work with your application.Then map over the array you get back from the response of the get request. Of course change the names and stylings to suit your needs, I'm using Bootstrap to make things easy to understand. Hope this helps.
import React, { Component } from 'react'
import axios from 'axios';
import cookie from 'react-cookie';
import { Modal,Button } from 'react-bootstrap'
import { API_URL, CLIENT_ROOT_URL, errorHandler } from '../../actions/index';
class NameofClass extends Component {
constructor(props) {
super(props)
this.state = {
classrooms: [],
profile: {country: '', firstName: '', lastName: '', gravatar: '', organization: ''}
}
}
componentDidMount(){
const authorization = "Some Name" + cookie.load('token').replace("JWT","")
axios.get(`${API_URL}/your/endpoint`, {
headers: { 'Authorization': authorization }
})
.then(response => {
this.setState({
classrooms:response.data.classrooms,
profile:response.data.profile
})
})
.then(response => {
this.setState({classrooms: response.data.profile})
})
.catch((error) => {
console.log("error",error)
})
}
render () {
return (
<div className='container'>
<div className='jumbotron'>
<h1>NameofClass Page</h1>
<p>Welcome {this.state.profile.firstName} {this.state.profile.lastName}</p>
</div>
<div className='well'>
{
this.state.classrooms.map((room) => {
return (
<div>
<p>{room.name}</p>
</div>
)
})
}
</div>
</div>
)
}
}
export default NameofClass

Resources