I am new to react and I have been learning it online.But I have some issues.Whenever I try to fetch the url it says
Syntax error: C:/xampp/htdocs/react-project/src/App.js: Unexpected token, expected ; (14:10).I have followed the same step as the video but also I am getting the problem.Here is the code
import React, { Component } from 'react';
import './App.css';
import Flat from './components/flat';
class App extends Component {
constructor(props){
super(props);
this.state={
flats:[]
}
}
componentDidMount(){
const url="https://raw.githubusercontent.com/lewagon/flats-boilerplate/master/flats.json";
fetch url()
.then(response =>response.json())
.then((data)=>{
console.log(data);
});
}
render() {
return (
<div className="app">
<div className="main">
<div className="search">
</div>
<div className="flats">
{this.state.flats.map((flat)=>{
return <Flat flat ={flat} />
})}
</div>
</div>
<div className="map">
</div>
</div>
);
}
}
export default App;
Here is the error message
I would be grateful for your help and sorry if I've done dumb mistake
It is simple syntax error.It should be :
fetch(url).then(response => response.json()).then(//dosomething)
You should replace fetch url() with fetch(url) in line 14
You can change the fetch like this way
const url="https://raw.githubusercontent.com/lewagon/flats-boilerplate/master/flats.json";
fetch(url, {
method: 'GET',
}).then(response =>response.json())
.then((data)=>{
console.log(data);
});
Related
DataInsertSelect.jsx
import React from 'react'
import axios from 'axios'
import Data from './Data'
class DataInsertSelect extends React.Component {
constructor() {
super();
this.state = {
datam: ""
};
}
componentDidMount() {
const axios = require('axios');
// Make a request for a user with a given ID
axios.get('https://jsonplaceholder.typicode.com/todos?_limit=5')
.then( function (response) {
// handle success
console.log(response);
})
.catch(function (error) {
// handle error
console.log(error);
})
.then(function () {
// always executed
});
}
render() {
return (
<div className="container">
<div class="row">
<div className="col-sm-6 offset-sm-5">
{this.state.datam.map(joke=> (
<Data key={joke.id} title={joke.title} />
))}
</div>
</div>
<div className="col-sm-10 offset-sm-2"><br/>
<form class="form-inline" action=" " method="post" >
<div class="form-group">
<label for="email">FIRSTNAME:</label>
<input type="text" name="data1"
class="form-control" id="email" />
</div>
<div class="form-group">
<label for="pwd">LASTNAME:</label>
<input type="text" name="data2"
class="form-control" id="pwd" />
</div>
<button type="submit" class="btn btn-danger">Submit</button>
</form>
</div>
</div>
);
}
}
export default DataInsertSelect;
Data.jsx
import React from 'react'
class Data extends React.Component {
render() {
return (
<h3>{this.props.title}</h3>
);
}
}
export default Data;
Using console.log(response); outputs the 5 row data but I want to store the axios response to a variable and update the state and it needs to be displayed in the application.
Here also I am facing the error:
TypeError: this.state.datam.map is not a function.
I tried a lot but could not fix it. I am an absolute begginer at React and axios.
I hope this is clear . Thanks In advance.
The error :TypeError: this.state.datam.map is not a function you are getting because your this.state.datam is an empty string "", as declared in Constructor. And map is function available for Arrays and not string.
FIX: in constructor, instead use: this.state={ datam : [] }
To save the axios response into your state,do something like this:
axios.get('https://jsonplaceholder.typicode.com/todos?_limit=5')
.then((response)=> {
console.log(response);
this.setState({datam:response.data});
})
Hope this helps!
This example could help you
import React, { Component } from 'react'
import Axios from 'axios';
export default class example extends Component {
constructor(props) {
super(props)
this.state = {
users :[]
}
}
componentDidMount(){
Axios.get('http://127.0.0.1:8000/users/')
.then(function (response) {
this.setState({
users: response.data,
});
})
.catch(function (error) {
console.log(error);
})
};
render() {
return (
{
{ users.lenght >0 ? (
<tbody>
<tr>
<td>{this.state.id}</td>
<td>{this.state.username}</td>
<td>{this.state.email}</td>
</tr>
</tbody>
):(
<h1>No data available!</h1>
)
}
}
)
}
}
Trying to learn react, following a tutorial. I am having difficulty getting data from my API (mongodb using whatwg-fetch") and rendering the items. The database is running, and no errors in react. The developer tools reports "props object empty", did some research and narrowed it down to the asynchronous nature of react. Apparently, it is rendering before data comes in. However, I have implemented a promise and yet no change in result. Any help will be greatly appreciated.
I have added a promise.
// App.js file
import React, {Component} from 'react';
import logo from './logo.svg';
import './App.css';
import Product from "../components/product/product"
import HttpService from "../services/http-service";
const http = new HttpService();
class App extends Component {
constructor(props) {
super(props);
this.state = {
products: []
}
// Bind functions
this.loadData = this.loadData.bind(this);
this.productList = this.productList.bind(this);
this.loadData()
};
loadData = () => {
let self = this;
http.getProducts().then(data => {
self.setState({products: data})
}, err => {
});
}
productList = () => {
const list = this.state.products.map((product) =>
<div className="inItems" key={product._id}>
<Product title={product.title} price={product.price} imgUrl=
{product.imgUrl} />
</div>
);
console.log(list)
return (list)
}
render() {
return (
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<p>
Welcome
</p>
<div className="container App-main">
<div className="items">
<h1>List Of Products</h1>
{this.productList()}
</div>
</div>
</header>
</div>
);
}
}
export default App;
// service.js file
import "whatwg-fetch";
class HttpService {
getProducts = () => {
let promise = new Promise((resolve, reject) => {
fetch("http://localhost:7500/product-list", {mode: "no-cors",
credentials: 'include' })
.then(res => {
resolve(res.json())
}).catch(err => {
if (err) throw err;
reject(err)
})
});
return promise;
}
}
export default HttpService;
Expecting items to display on screen. Nothing displays and no errors in console.
you need to await Data (const data = await http.getProducts()) or simply use axios https://www.npmjs.com/package/axios
.then mean once you receive response, you gonna do something, still the outer scope will keep running and still data is empty
I am following the current tutorial:
Youtube tutorial at 12:51 mins.
I expect to see bunch of posts on my screen but my screen remains blank.
It appears I have followed everything told in the tutorial.
import React, { Component } from 'react';
class Posts extends Component {
constructor(props) {
super(props);
this.state = {
posts: []
}
}
componentWillMount() {
fetch('https://jsonplaceholder.typicode.posts')
.then(res => res.json())
.then(data => this.setState({posts: data}))
}
render() {
const postItems = this.state.posts.map(post => (
<div key={post.id}>
<h3>{post.title}</h3>
<p>{post.body}</p>
</div>
));
return (
<div>
<h1>Posts</h1>
{ postItems }
</div>
);
}
}
export default Posts;
and
import React, { Component } from 'react';
import './App.css';
import Posts from './components/Posts'
class App extends Component {
render() {
return (
<div className="App">
<Posts />
</div>
);
}
}
export default App;
My browser screen remains blank and I do not see any errors on console.
What am I missing ?
Don't know about the tutorial but it looks outdated...
Here is your App.js (parent component):
import React, { Component } from 'react';
import Posts from './Posts';
export default class App extends Component {
state = { posts: [] };
//fetch the posts and store them in the state
componentDidMount() {
fetch('https://jsonplaceholder.typicode.com/posts')
.then(response => response.json())
.then(posts => this.setState({ posts }))
.catch(error => console.log(error));
}
render() {
return (
<div>
{/* pass the state (posts) as props to Posts */}
<Posts posts={this.state.posts} />
</div>
);
}
}
Here is your Posts.js:
import React from 'react';
// No need for a class based comp
// destructure the props and you have all your data
const Posts = ({ posts }) => (
<div>
{posts.map(post => (
<div key={post.id}>
<h3>{post.title}</h3>
<p>{post.body}</p>
<hr />
</div>
))}
</div>
);
export default Posts;
Live Demo: https://jsfiddle.net/ctszdue9/7/
Try putting side effect/ api call inside
componentDidMount() { }
Change URL
https://jsonplaceholder.typicode.posts/
TO
https://jsonplaceholder.typicode.com/posts
I'm fetching data of list of champions from JSON file, and am trying to make a link to view each champ and am not sure how to pass img property in the link from react-router.
I tried using state: champion.img but it's not giving anything. Any ideas how can I pass the image value?
import React, { Component } from 'react'
import axios from 'axios'
import { Link } from 'react-router-dom';
class PersonList extends Component {
state = {
persons: [],
name:"",
champs: [],
isLoaded: false,
Aatrox:''
}
componentDidMount(){
axios({
method: 'get',
url: 'https://api.myjson.com/bins/blcps'
})
.then(res => {
this.setState({ persons: res.data[1]})
console.log(res.data[0].name);
console.log('ldldl');
const champions = res.data.map((champion) => {
console.log(champion.name)
console.log(this.state.champs.name)
return <div classname="container-fluid">
<div classname="row">
<p>ldldl</p>
<h2 className="card-title">{champion.name}</h2> </div>
<img src={champion.img} />
<Link to={{ pathname:`/champions/${champion.name}`,// undefined state: {champion.img} }} > {champion.name} </Link>
</div>
})
this.setState({ champs: champions, isLoaded: true });
})
}
render() {
return (
<ul>
{this.state.isLoaded ? <div>{this.state.champs}</div> : <div>.</div>}
</ul>
)
}
}
export default PersonList;
when you console.log(champion.img), do you get a full url ? if not you have to place the complete url of the file not just filename for it to work. How you do this depends on what was returned from the server.
I'm following this online tutorial on using Fetch to consume API data; I was able to get the application to Fetch data using the JSON url provided in the tutorial. However, I made some modifications to the code and attempted to fetch data from a different JSON file and got an error:
Here is the code:
import React, { Component } from 'react';
import {render} from "react-dom";
import Navbar from '../components/Navbar.jsx';
import Footer from '../components/Footer.jsx';
import './ClientInfo.css';
class ClientInfo extends Component {
constructor(){
super();
this.state= {
titles: []
};
}
componentWillMount(){
fetch('https://jsonplaceholder.typicode.com/todos')
.then(results => {
return results.json();
}).then(data => {
let titles = data.results.map((til) => {
return(
<div key={til.results}>
<p>{til.title} </p>
</div>
)
})
this.setState({titles: titles});
console.log("state", this.state.titles);
})
}
render() {
return (
<div>
<Navbar />
<div className="container">
<div className="clientContainer">
{this.state.titles}
</div>
</div>
<Footer />
</div>
);
}
}
export default ClientInfo
The error occurs at this line:let titles = data.results.map((til) => {. could I get some help as what am doing wrong?
data.results - not array. Array data.map