React: cant get data via API - reactjs

I am new here and with React. I tried to get data via APı but I could not get any. Also, I did not get any error message as well. This is my code. I tried to add if statement to check whether data is fetched or not. When I check console I got the error message. Where did I wrong? Thanks for your time.
import React, {Component} from "react";
class PokemonList extends Component {
constructor(props) {
super(props);
this.state = {
error: null,
isLoaded: false,
items: [],
};
}
componentDidMount() {
fetch('https://pokeapi.co/api/v2/pokemon?limit=20')
.then(res => res.json())
.then(
(result) => {
this.setState({
isLoaded: true,
items: result.items
});
},
// Note: it's important to handle errors here
// instead of a catch() block so that we don't swallow
// exceptions from actual bugs in components.
(error) => {
this.setState({
isLoaded: true,
error
});
}
)
}
render() {
const { error,isLoaded, items } = this.state;
if (error) {
return <div>Error: {error.message}</div>;
} else if (!isLoaded) {
return <div>Loading...</div>;
} else {
return (
<ul>
{items ? items.map(item => (
<li>
<p key={item.id}>{item.name}</p>;
</li>
)) :
console.log('no data')}
</ul>
);
}
}
}
export default PokemonList;

The Pokémon items you're trying to get have a results key, not items. So replace result.items with result.results and see what happens.

Related

Display data from state

I have took data from firebase and want to display:
class DisplayVisit extends Component{
state = {
allVisit: [] //this I have changed
}
componentDidMount(){
this.getVisit();
}
getVisit = async() => {
try {
const currentVisit = await doctorvisit.get();
this.setState({ allVisit: currentVisit })
this.state.allVisit.forEach(element => {
console.log(element.data()) // i see data, fields like => {user, info, visitAt}
});
} catch(error) {
console.log('error getting visits ', error);
}
}
render(){
return(
{Object.keys(this.state.allVisit).map(key => (
<span>{this.state.allVisit[key].info}1</span>
))}
)
}
}
But nothing is render.
I tried also {key.info} but nothing is render.
Screen from console:
Log from console.log(this.state.allVisit);:
If i see good, you're setting the state allVisit to currentVisit, wich is a single object.
Either your allVisit property in state is an array with visit objects inside, or simply apply currentVisit in state as a single object.
In the meantime, you're looping a single object, if its what you're trying to achieve, remove the .info after the [key] and you will have all you're property displayed
If you want to loop through nested objects or an array of object provide more informations
Update, i'll tried to guess your data so try with this code
export default class DisplayVisit extends Component {
state = {
allVisit: [] //this I have changed
};
componentDidMount() {
this.getVisit();
}
getVisit = async () => {
try {
const { docs } = await doctorvisit.get();
//try this if first not working
const allVisitsData = await doctor.visit.get()
this.setState({ allVisit: docs });
//try this if first not working
//this.setState({ allVisit: allVisitData.docs });
//or this
} catch (error) {
console.log("error getting visits ", error);
}
};
render() {
return (
<div>
{this.state.allVisit.map((visit) => (
<span key={visit.info}>{visit.info} 1</span>
))}
</div>
);
}
}
I did it based on Google docs:
class DisplayVisit extends Component{
state = {
allVisit: []
}
componentDidMount(){
this.getVisit();
}
getVisit = async() => {
try {
await doctorvisit.get().then(querySnapshot => {
const data = querySnapshot.docs.map(doc => doc.data());
this.setState({allVisit : data});
})
} catch(error) {
console.log('error getting visits ', error);
}
}
}
Documentation:
https://firebase.google.com/docs/firestore/query-data/get-data?hl=en
and blog/post:
https://rnfirebase.io/firestore/usage

JSON Data Object Handling in React

Cant figure it out how to extract data from parsed and stored json object from state ... i have tried many ways but getting errors (data from openweathermap)
class App extends Component {
constructor(props) {
super(props);
this.state = {
isLoading: true,
data: null
};
}
getWeather(url) {
fetch(url)
.then(res => res.json())
.then(data =>
this.setState({
isLoading: false,
data: data
})
)
.catch(error => console.log("Error Loading data " + error));
}
componentDidMount() {
navigator.geolocation.getCurrentPosition(position => {
const url = `${API}lat=${position.coords.latitude}&lon=${position.coords.longitude}&${APPID}`;
this.getWeather(url);
});
}
render() {
return (
<div>
{console.log(this.state.data)}
{/*renders json*/}
<h1>{this.state.data.name}</h1>
</div>
);
}
}
I believe you might be getting cannot read property 'name' of null. Not sure about the exact error but something like that.
Try to use
<h1>{ this.state.data && this.state.data.name }</h1>
Till the time API is not giving the response, your data in the state is null so you cannot access data.name.

React Fetch Cannot read property 'map' of undefined

I'm getting Cannot read property 'map' of undefinedin my React app - while that typically means that I'm searching for the incorrect data type (object vs. array, for instance), I'm unable to console.log my API URL, which makes me think something else is wrong.
Here's my code, everything exists in my App.js file so it's not an issue with calling other components or anything:
import React, { Component } from 'react';
import './App.css';
const APIURL = `https://api.openbrewerydb.org/breweries?`;
const citySearch = `by_state=new_york`;
class App extends Component {
constructor() {
super()
this.state = {
error: null,
isLoaded: false,
breweries: []
};
}
componentDidMount() {
fetch(APIURL + citySearch)
.then(res => res.json())
.then(
(result) => {
this.setState({
isLoaded: true,
breweries: result.breweries
});
},
(error) => {
this.setState({
isLoaded: true,
error
});
}
)
}
render() {
const { error, isLoaded, breweries } = this.state;
if (error) {
return <div>Error: {error.message}</div>;
} else if (!isLoaded) {
return <div>Loading...</div>;
} else {
return (
<ul>
{breweries.map(brewery => (
<li key={brewery.id}>
{brewery.name} {brewery.city}
</li>
))}
</ul>
);
}
}
}
export default App;
Here's the data I'm trying to get - if I copy and paste my APIURL into my browser, I get the data - so I'm not sure where undefined is coming from:
[{"id":4581,"name":"Adirondack Toboggan Company Microbrewery","brewery_type":"micro","street":"202A W Main St","city":"Gouverneur","state":"New York","postal_code":"13642-1334","country":"United States","longitude":"-75.4748923846074","latitude":"44.3323731052224","phone":"3157716313","website_url":"http://www.adktoboggan.net","updated_at":"2018-08-24T15:37:58.899Z","tag_list":[]}, (AND SO ON)...
As I've just started this app, I'm just trying to make sure my fetch request works so I can build out components.
Am I getting undefined because of how I'm searching for the data (which seems to be the solution to other questions like mine) or is something else going on that prevents me from even logging my APIURL const?

TypeError: this.state.patients.map is not a function

i am new in react js,and i am learning to create a React application and I got a problem with mapping function:
Here's my request and how I am attempting to render the data:
class Patients extends Component {
constructor(props) {
super(props)
this.state = {
patients: []
}
}
componentDidMount() {
api.getPatients()
.then( patients => {
console.log( patients)
this.setState({
patients: patients
})
})
.catch(err => console.log(err))
}
render() {
return (
<div className=" Patientss">
<h2>List of Patient</h2>
{this.state.patients.map((c, i) => <li key={i}>{c.name}</li>)}
</div>
);
}
}
export default Patients;
here my api calling
import axios from 'axios';
const service = axios.create({
baseURL: process.env.NODE_ENV === 'production' ? '/api' : 'http://localhost:3000/patient',
});
const errHandler = err => {
console.error(err);
throw err;
};
export default {
service: service,
getPatients() {
return service
.get('/')
.then(res => res.data)
.catch(errHandler);
},
}
and I get the following error:
TypeError: this.state.patients.map is not a function
i've try to use slice aswell but it didnt work, anyone know whats wrong with my code?`
Based on the symptoms (heh), the patients object you get in api.getPatients() isn't an array.
console.log() it to see what it actually is.
EDIT: Based on the comments, the patients object looks like
{
count: 24,
patient: [...],
}
so the this.setState() call needs to be
this.setState({patients: patients.patient})
You can also do something like this as an conditional rendering. It will check that if this.state.patient exists then only it will go ahead and call this.state.patients.map function. It will also ensure that you don't receive any errors later on due to bad responses.
I updated your Patients Code example.
class Patients extends Component {
constructor(props) {
super(props)
this.state = {
patients: []
}
}
componentDidMount() {
api.getPatients()
.then( patients => {
console.log( patients)
this.setState({
patients: patients
})
})
.catch(err => console.log(err))
}
render() {
return (
<div className=" Patientss">
<h2>List of Patient</h2>
{ this.state.patients && this.state.patients.map((c, i) => <li key={i}>{c.name}</li>)}
</div>
);
}
}
export default Patients;
I hope it helps. Thanks!!

React Application 'npm test' Warning

I created a React application for practice. It works in my browser; however when I ran "npm test" from my terminal, it giving me a warning "Can only update a mounted or mounting component. This usually means you called setState, replaceState, or forceUpdate on an unmounted component. Please check the code for the FetchOne component."
I checked the FetchOne component but I couldn't figure it out. Is there anybody help me out, thank you!
Here is my code:
import React, {Component} from 'react';
const API = 'https://hn.algolia.com/api/v1/search?query=';
const DEFAULE_TITLE = 'N/A title';
class FetchOne extends Component{
constructor(){
super()
this.state=({
hits: [],
isLoading: false,
error: null,
})
}
componentDidMount(){
this.setState({ isLoading: true })
fetch(API)
.then(response =>{
if(response.ok){
return response.json()
}else{
throw Error('Somethig went wrong...')
}
} )
.then( data => this.setState({
hits: data.hits,
isLoading: false,
}))
.catch(error => this.setState({
error,
isLoading: false
}))
}
render(){
const { hits, isLoading, error } = this.state;
if(isLoading){
return <p> Loading... </p>
}
if(error){
return <p>{error.message}</p>
}
return(
<div>
{hits.map(data =>
<ul key={data.objectID}>
<li>Title:<a href={data.url}> {data.title || DEFAULE_TITLE}</a></li>
<li>Author: {data.author}</li>
<li>Points: {data.points}</li>
</ul>
)}
</div>
)
}
}
export default FetchOne
Click HERE for Error Massage Screenshot
I had a similar issue previously. The issue related to the fact that the component had unmounted but I was still making a setState call. This can happen when using async functions and passing a callback which includes setState to test if this is the case.
Create
componentWillUnmount() {
console.log("Fetch One Unmounted");
}
Then see if the setState is called after the message appears.
componentDidMount(){
this.setState({ isLoading: true })
fetch(API)
.then(response =>{
if(response.ok){
return response.json()
}else{
throw Error('Somethig went wrong...')
}
} )
.then( data => this.setState({
hits: data.hits,
isLoading: false,
}, () => {console.log("setState Called")}))
.catch(error => this.setState({
error,
isLoading: false
}))
}

Resources