I am trying to build a single-page React app, which loads content from an API using Axios.
I have created the component called "Importapi" and called it in the App.js file as yet nothing is showing up.
Does anyone have an idea as to why this is happening?
Importapi - Import Component
import React, { Component } from 'react';
import axios from "axios";
import "./index.css";
export class Importapi extends Component {
constructor() {
super();
this.state = {
trails: [],
}
//this.handleSubmit = this.handleSubmit.bind(this);
};
componentDidMount() {
axios.get("https://www.hikingproject.com/data/get-trails?lat=46.589519&lon=7.912295&maxDistance=100&maxResults=15&key=200490043-7294b2e6976c168d4e44877bf48ef553")
.then(response => {
console.log(response.data);
})
.catch(error => {
console.log(error);
});
}
render() {
return (
<div className="container2">
<div className="container1">
{this.state.trails}
</div>
</div>
)
};
};
export default Importapi;
App.js - Single page React App
import React from 'react';
import logo from './logo.png';
import './App.css';
import Import from './import.js';
import Importapi from './axios-api'
function App() {
return (
<div className="App">
<header>
<title>Hikeero</title>
</header>
<nav>
<div className="nav-bar logo">
<button>BACK</button>
</div>
<div className="nav-bar items">
</div>
<button> HOME </button>
</nav>
<div align="right" >
<br/>
</div>
<h1>Hikeero.</h1>
<Import />
<Importapi />
<header className="App-header">
<a
className="App-link"
href="/import.js/"
target="_blank"
rel="noopener noreferrer"
>
<br/>
<br/>
<br/>
Click to Start
</a>
</header>
</div>
);
}
export default App;
There are no errors, just the API information isn't showing up.
You have to do this.setState({ trails : response.data }) just below console.log(response.data); to show the content on component. Thus the API response will be set into state with key name of trails.
componentDidMount() {
axios.get("https://www.hikingproject.com/data/get-trails?lat=46.589519&lon=7.912295&maxDistance=100&maxResults=15&key=200490043-7294b2e6976c168d4e44877bf48ef553")
.then(response => {
// here once you receive response
// put the response data into state of the component
// as written below
this.setState({trails: response.data})
})
.catch(error => {
console.log(error);
});
}
Related
I have two page with same logic but different content and i want to use the same object but parse different json content.
Projects and Experience page use the same ProjectList and Project. I want to pass different content to Projects.js and Experience.js
Project:
import React, {Component} from 'react';
import Navigation from "../components/Nagivation";
import ProjectList from "../components/experience/ProjectList";
import { portfolioData } from '../data/portfolioData';
export default class Projects extends Component {
state = {
projects:portfolioData
};
render() {
let {projects} = this.state;
return (
<div className="portfolio">
<Navigation/>
{
<ProjectList
item={projects}
/>
}
</div>
);
}
};
ProjectList
import React, {Component} from 'react';
import Project from "./Project";
export default class ProjectList extends Component {
render() {
console.log(this.props.item)
let {projects} = this.props.item;
return (
<div className="portfolioContent">
<h3 className="radioDisplay">Test</h3>
<div className="projects">
{
projects.map(item => {
return (
<Project
key={item.id}
item={item}
/>
)
})
}
</div>
</div>
);
}
}
I have Uncaught TypeError: Cannot read properties of undefined (reading 'map') on the line <div className="projects">
Project.js
import React, {Component} from 'react';
export default class Project extends Component {
state = {
showInfo: false
}
handleInfo = () => {
this.setState({
showInfo:!this.state.showInfo
})
}
render() {
let {name, periode, info, picture} = this.props.item
return (
<div className="project">
<h5>{periode}</h5>
<h3>{name}</h3>
<img src={picture} alt="" onClick={this.handleInfo} />
//some stuffs
);
}
}
I don't want to use map, because i want to iterate only in ProjectList.
i have created a demo file where i have set up a dispatcher and same is been connecting through connect function to the App component.
But while I'm trying to access props in component, its showing me blank rather it should have a dispatch function.
Please assist to get through.
import App from "../Components/App";
import { connect } from "react-redux";
import { buyCartAction } from "../Services/Action";
const mapStateToProps =()=>{
}
const mapDispatchToProps = dispatch => (
{ buyThisProduct: data => dispatch(buyCartAction(data)) }
)
export default connect(mapStateToProps, mapDispatchToProps)(App)`
import React from "react"
function App(props) {
console.log(props)
return (
<>
<h1 className="heading">Good Day Page</h1>
<div className="cart_bar">
<img className="img_scale" src="https://images.news18.com/ibnlive/uploads/2021/08/1628224744_hp-envy-14-laptop-1600x900.jpg" alt="Lenovo Laptop" />
<div className= "child_cart">
<p className="info_bar">Lenovo Probook 15 series </p>
<span className="info_bar_price">Price at just Rs: 37000/-</span>
<br />
<button className="btn_buy"}>Buy</button>
</div>
</div>
</>
)
}
export default App;
Action creator as below:
import { buy } from "../Constants"
export const buyCartAction =(data) =>{
return{
type: buy,
data: data
}
}
Console output as below.
enter image description here
import React, { Component } from 'react';
import Navbar from './components/Navbar';
import Landingpage from './components/Landingpage';
import Mainbody from './components/Mainbody';
import './App.css';
import axios from 'axios';
import { FORTNITE_IO } from './config'
class App extends Component {
state = {
itemShop: {},
test: 'damiisdandy'
};
getItemShop = () =>
axios.get('https://fortniteapi.io/shop?lang=en', {
headers: {
Authorization: FORTNITE_IO
}
})
.then(res => res.data)
.catch(err => err);
componentDidMount() {
this.setState({itemShop: this.getItemShop()})
this.setState({test: 'feyi'})
console.log(this.state)
}
render() {
return (
<div className="App">
<div className="sil">
<img style={{ zIndex: 0 }} src="./img/glider-sil.png" alt=""/>
</div>
<Navbar />
<Landingpage />
<Mainbody />
<footer>
<img src="./img/midas3.png" alt="geng"/>
<img className="footer-img" src="./img/midas1.png" alt="geng"/>
</footer>
</div>
)
}
}
export default App;
I am new to react,
i am making a request with axios and trying to update my state with the response data
I am trying to update the state with this.Setstate() but it doesn't seem to update the state at all.. please i need help!!!!!!
The best thing for you to do is to make the request , when the response comes in then you call set state . When you call componentDidMount and set state the request does not come in immediately. So the best thing to do.
getItemShop = () => {
axios.get('https://fortniteapi.io/shop?lang=en', {
headers: {
Authorization: FORTNITE_IO
}
})
.then(res => {
this.setState({itemShop: res.data})
}
.catch(err => err);
}
Remove console.log(this.state) and use the React devtools extension to view state instead.
I have a form that submit some data and i have item component that has a delete button that delete an item but when i submit something it submit and delete the item in the same time
import React, {Component} from 'react';
import ApiClient from './apiClient';
import './MessageForm.css';
class MessageForm extends Component {
constructor(props){
super(props);
this.state = {
submitted: false
}
}
handleSubmit = async (event) => {
event.preventDefault();
const messageData = new FormData(event.target);
await ApiClient.addMessage({
license_plate: messageData.get('license'),
body: messageData.get('body')
});
// console.log("submitted");
// this.props.refreshList();
};
render() {
return(
<form onSubmit={this.handleSubmit} className="MessageForm">
<div>
<label htmlFor="license">License Plate</label>
<input id="license" name="license" type="text" />
</div>
<div>
<label htmlFor="body">Message</label>
<textarea id="body" name="body" type="text"/>
</div>
<div>
<input type="submit" value="Submit"/>
</div>
</form>
)
}
};
export default MessageForm;
this is the item component
import React from 'react';
import moment from 'moment';
import SocailShare from './SocialShare.css'
import { FacebookShareButton, LinkedinShareButton,
TwitterShareButton,
TelegramShareButton,
WhatsappShareButton,
EmailShareButton,} from 'react-share';
import { FacebookIcon, EmailIcon,
TwitterIcon,
TelegramIcon,
WhatsappIcon,
LinkedinIcon,} from 'react-share';
import {
FacebookShareCount,
PinterestShareCount,
VKShareCount,
OKShareCount,
RedditShareCount,
TumblrShareCount,
} from 'react-share';
import './MessageItem.css';
export default ({ id, submission_date, license_plate, body, handleDelete }) => {
var timePosted = moment(submission_date).format('DD/MM/YYYY - HH:mm');
const onDelete = (id) => {
handleDelete(id);
}
return (
<li className="MessageItem">
<span>Time: {timePosted} - </span>
<span>To license: {license_plate} : </span>
<span> {body} </span>
<button onClick={onDelete(id)}>X</button>
<div className="SocialShare">
<FacebookShareButton url="https://github.com/nygardk/react-share#readme" >
<FacebookIcon size={30}/>
<FacebookShareCount url="https://github.com/nygardk/react-share#readme">
{shareCount => (
<span className="myShareCountWrapper">{shareCount}</span>
)}
</FacebookShareCount>
</FacebookShareButton>
<TwitterShareButton url="https://github.com/nygardk/react-share#readme">
<TwitterIcon size={30}/>
</TwitterShareButton >
<EmailShareButton url="https://github.com/nygardk/react-share#readme">
<EmailIcon size={30}/>
</EmailShareButton>
</div>
</li>
);
};
and this is the message list component that renders the message item
import React, { Component } from 'react';
import './MessageList.css';
import MessageItem from './MessageItem';
import ApiClient from './apiClient'
class MessageList extends Component {
constructor(props) {
super(props);
}
handleOnDelete = async (id) => {
console.log(id + "deleted")
await ApiClient.deleteMessage(id);
this.props.refreshList();
}
render() {
const {
messages
} = this.props;
messages.sort(function(a,b){
//the list will be ordered in descending date order (most recent first)
return new Date(b.submission_date) - new Date(a.submission_date);
});
const $messages = messages.map((message) => <MessageItem handleDelete={this.handleOnDelete} key={message._id} {...message} />);
return (
<section className="MessageList">
<h1>Message Board</h1>
<ul>
{$messages}
</ul>
</section>
)
}
}
export default MessageList;
and this is the app component where everything is rendered
import React, { Component} from 'react';
import {BrowserRouter, Route, Switch} from 'react-router-dom';
import ApiClient from './apiClient';
import './App.css';
import MessageForm from './MessageForm';
import MessageList from './MessageList';
class App extends Component {
constructor(props){
super(props);
this.state = {
messages: []
}
}
componentDidMount = async () => {
this.refreshList();
}
refreshList = async () => {
const messages = await ApiClient.getMessages();
this.setState({
messages
})
}
render () {
return (
<BrowserRouter>
<div className="App">
<header className="App-header">
<h1>Hello License</h1>
<p>Send your messages to a plate number easily!</p>
</header>
<MessageForm refreshList = {this.refreshList}/>
</div>
<Switch>
<Route exact path="/api" render ={props => <MessageList refreshList = {this.refreshList} messages={this.state.messages} {...props}/> }/>
</Switch>
</BrowserRouter>
)
}
};
export default App;
in your item component, this line <button onClick={onDelete(id)}>X</button> is your problem.
What you are inadvertently saying is that when the DOM renders this component, it should call onDelete right away, and the onClick handler will refer to void. To avoid this, what you want is to pass in a function like so: <button onClick={(id) => onDelete(id)}>X</button>
I have a list of 50 photos which I will get from an API. When the user clicks on any photo it should open up on the right side component.
When a photo in the right side component is clicked it should scroll down (if the image is not at top) the the place in the page where that image is present.
import React from 'react';
import axios from 'axios';
import '../App.css';
class Dashboard extends React.Component {
constructor(props) {
super(props);
this.state={
image:'abc',
}
}
imageload(appendimage){
this.setState({
image:appendimage
})
}
componentWillMount() {
axios.get('http//api')
.then((res) => this.setState({
results: res.data
}))
.catch((error)=>{
console.log(error)
})
}
render() {
return (
<div>
<div className="left">
<img width="373" height="230" alt="img3" id="mytarget"
onClick={this.imageload.bind(this,"https://i.ytimg.com.jpg")}
src="https://i.ytimg.com/vi/.jpg"
/>
</div>
<div className="right>
<img src={this.state.ima} height={510} width={400}
alt="placeholderimg"
style={{position:"fixed"}}
className={classes.staticimg}
onClick={this.imageredirect.bind(this)}
/>
</div>
</div>
);
}
}
export default withStyles(style)(Dashboard);