The below code renders a list of planets (from this API: https://swapi.dev/).I'm trying to find a way to make my planets clickable. When a specific planet is clicked in the list, it should open up a detail page with specific info (pulled from API) on the planet that has been clicked. Can I do this with or ? What is the best practice way to do this?
import React, { PureComponent } from 'react'
import axios from "axios";
class Home extends PureComponent {
constructor(props) {
super(props)
this.state = {
planets: [],
filteredPlanets: []
}
this.handleChange = this.handleChange.bind(this)
}
handleChange(e){ // eslint-disable-next-line
let planetssearchlist = this.state.planets.filter(planet => {
if(planet.name){
if(planet.name.toLowerCase().includes(e.target.value.toLowerCase())){
return true
}
}
})
this.setState({
filteredPlanets: planetssearchlist
})
}
componentDidMount(){
axios({
method: "GET",
url: "https://swapi.dev/api/planets/"
})
.then(response => {
console.log(response)
let planetslist = response.data.results;
this.setState({planets: planetslist, filteredPlanets: planetslist})
})
.catch(error => {
console.log("You've made an error with the planets load charles: ",error)
})
}
render() {
return (
<div>
<h1>Star Wars Planets</h1>
<form>
<input placeholder="searchbar" type="text" onChange={this.handleChange}></input>
</form>
{
this.state.filteredPlanets.map((planet,i) => (
<p key={i}>{planet.name}</p>
))
}
</div>
)
}
}
export default Home
Add a new function to get the planet info. In your map add onClick event handler to get the planet info for the clicked planet.
Add two new variable to your state
this.state = {
planets: [],
filteredPlanets: [],
planetInfo: {},
isGettingPlanetInfo: false,
};
Add a function to get the planet info
getPlanetInfo = url => {
this.setState({
isGettingPlanetInfo: true
})
axios({
method: "GET",
url: url
})
.then(response => {
console.log(response.data)
this.setState({
planetInfo: response.data,
isGettingPlanetInfo: false,
})
})
.catch(error => {
this.setState({
isGettingPlanetInfo: false
})
console.log(
"You've made an error with the planets load charles: ",
error
);
});
};
Add on click event handler to the planet
{this.state.filteredPlanets.map((planet, i) => (
<p onClick={() => this.getPlanetInfo(planet.url)} key={i}>
{planet.name}
</p>
))}
Home component
import React, { PureComponent } from 'react';
import axios from 'axios';
export default class Home extends PureComponent {
constructor(props) {
super(props);
this.state = {
planets: [],
filteredPlanets: [],
planetInfo: {},
isGettingPlanetInfo: false,
};
this.handleChange = this.handleChange.bind(this);
}
handleChange(e) {
// eslint-disable-next-line
let planetssearchlist = this.state.planets.filter((planet) => {
if (planet.name) {
if (planet.name.toLowerCase().includes(e.target.value.toLowerCase())) {
return true;
}
}
});
this.setState({
filteredPlanets: planetssearchlist,
});
}
getPlanetInfo = (url) => {
this.setState({
isGettingPlanetInfo: true,
});
axios({
method: 'GET',
url: url,
})
.then((response) => {
console.log(response.data);
this.setState({
planetInfo: response.data,
isGettingPlanetInfo: false,
});
})
.catch((error) => {
this.setState({
isGettingPlanetInfo: false,
});
console.log(
"You've made an error with the planets load charles: ",
error
);
});
};
componentDidMount() {
axios({
method: 'GET',
url: 'https://swapi.dev/api/planets/',
})
.then((response) => {
console.log(response);
let planetslist = response.data.results;
this.setState({ planets: planetslist, filteredPlanets: planetslist });
})
.catch((error) => {
console.log(
"You've made an error with the planets load charles: ",
error
);
});
}
render() {
return (
<div>
<h1>Star Wars Planets</h1>
<form>
<input
placeholder='searchbar'
type='text'
onChange={this.handleChange}
/>
</form>
{this.state.filteredPlanets.map((planet, i) => (
<p onClick={() => this.getPlanetInfo(planet.url)} key={i}>
{planet.name}
</p>
))}
<hr />
{this.state.isGettingPlanetInfo ? (
<p>getting planet info...</p>
) : typeof this.state.planetInfo === 'object' &&
Object.keys(this.state.planetInfo).length ? (
<div>
<p>name: {this.state.planetInfo.name}</p>
<p>climate: {this.state.planetInfo.climate}</p>
<p>population: {this.state.planetInfo.population}</p>
</div>
) : (
''
)}
</div>
);
}
}
With react router
import React, { PureComponent } from "react";
import axios from "axios";
import { BrowserRouter, Route, Switch, Link } from "react-router-dom";
class PlanetInfo extends React.Component {
state = {
url: "",
planetInfo: {},
isGettingPlanetInfo: false
};
getPlanetInfo = () => {
this.setState({
isGettingPlanetInfo: true
});
axios({
method: "GET",
url: this.state.url
})
.then(response => {
console.log(response.data);
this.setState({
planetInfo: response.data,
isGettingPlanetInfo: false
});
})
.catch(error => {
this.setState({
isGettingPlanetInfo: false
});
console.log(
"You've made an error with the planets load charles: ",
error
);
});
};
componentDidMount = () => {
this.setState(
{
url: this.props.location.state.planet.url
},
this.getPlanetInfo
);
};
render() {
return (
<div>
{this.state.isGettingPlanetInfo ? (
<p>getting planet info...</p>
) : typeof this.state.planetInfo === "object" &&
Object.keys(this.state.planetInfo).length ? (
<div>
<p>name: {this.state.planetInfo.name}</p>
<p>climate: {this.state.planetInfo.climate}</p>
<p>population: {this.state.planetInfo.population}</p>
</div>
) : (
""
)}
</div>
);
}
}
class Home extends PureComponent {
constructor(props) {
super(props);
this.state = {
planets: [],
filteredPlanets: []
};
this.handleChange = this.handleChange.bind(this);
}
handleChange(e) {
// eslint-disable-next-line
let planetssearchlist = this.state.planets.filter(planet => {
if (planet.name) {
if (planet.name.toLowerCase().includes(e.target.value.toLowerCase())) {
return true;
}
}
});
this.setState({
filteredPlanets: planetssearchlist
});
}
componentDidMount() {
axios({
method: "GET",
url: "https://swapi.dev/api/planets/"
})
.then(response => {
console.log(response);
let planetslist = response.data.results;
this.setState({ planets: planetslist, filteredPlanets: planetslist });
})
.catch(error => {
console.log(
"You've made an error with the planets load charles: ",
error
);
});
}
render() {
return (
<div>
<h1>Star Wars Planets</h1>
<form>
<input
placeholder="searchbar"
type="text"
onChange={this.handleChange}
/>
</form>
{this.state.filteredPlanets.map((planet, i) => (
<Link to={{ pathname: "/info", state: { planet: planet } }}>
<p key={i}>{planet.name}</p>
</Link>
))}
</div>
);
}
}
export default function Navigation() {
return (
<BrowserRouter>
<Switch>
<Route exact path="/" component={Home} />
<Route exact path="/info" component={PlanetInfo} />
</Switch>
</BrowserRouter>
);
}
Related
I have been doing js for about a month now, and I am writing this program where I am using clarifai API to see which celebrity a person on the photo resembles the most.
I want to pass the output as props to Rank component to render it, but
I get the
Type error: clarifaiResults.map is not a function at App.transformResponse
Basically, the response I want to pass as props is the
const clarifaiResults = response.outputs[0].data.regions[0].data.concepts[0].name;
part that I get in console.log now
I am assuming it's because there is no output yet when the app tries to render the component, but I can't figure out what's wrong with the code. Thank you!
App.js
import React, { Component } from 'react';
import './App.css';
import SignIn from './Component/SignIn/SignIn.js';
import Register from './Component/Register/Register.js';
import Particles from 'react-particles-js';
import Logo from './Component/Logo/Logo.js';
import Navigation from './Component/Navi/Navigation.js';
import ImageLinkForm from './Component/Form/ImageLinkForm.js';
import Rank from './Component/Rank/Rank.js'
import Clarifai from 'clarifai';
import FaceRecognition from './Component/Face/FaceRecognition.js';
import FaceComparison from './Component/Comparison/FaceComparison.js';
const app = new Clarifai.App({
apiKey: 'MYSUPERSECRETKEY'
});
const initialState = {
input: "",
imageUrl: "",
results: [],
route: "SignIn",
user: {
id: "",
name: "",
email: "",
entries: 0,
joined: "",
},
};
const particleOptions = {
particles: {
number: {
value: 40,
density: {
enable: true,
value_area: 800,
},
}
}
}
class App extends Component{
constructor() {
super();
this.state = initialState;
}
transformResponse = (response) => {
const clarifaiResults = response.outputs[0].data.regions[0].data.concepts[0].name;
const results = clarifaiResults.map((ingredient) => ({
ingredients: ingredient.name,
probablitiy: ingredient.value,
}));
this.setState({results: results.celebrityName});
return {results: []};
};
onInputChange = (event) => {
this.setState({input: event.target.value});
}
onSubmit = () => {
this.setState({imageUrl: this.state.input});
app.models
.predict(
Clarifai.CELEBRITY_MODEL,
this.state.input)
.then(response => {
console.log(response.outputs[0].data.regions[0].data.concepts[0].name)
if (response) {
fetch ('http://loclhost:3000', {
method: 'post',
headers: {'Conent-Type' : 'application/json'},
body: JSON.stringify({
input: this.state.user.input
})
})
.then((response) => response.json())
.then(count => {
this.setState(Object.assign(this.state.user, {entries:count}))
})
}
this.transformResponse(response);
})
.catch(err => console.log(err));
};
;
onRouteChange = (route) => {
if (route === 'signout'){
this.setState({isSignedIn: false})
} else if (route ==='home'){
this.setState({isSignedIn: true})
}
this.setState({route: route});
}
render() {
let { isSignedIn, imageUrl, route, results} = this.state;
return (
<div className="App">
<Particles className='particles'
params={particleOptions}
/>
<Navigation isSignedIn={isSignedIn} onRouteChange={this.onRouteChange}/>
{ route ==='home'
? <div>
<Logo />
<Rank
results = {results}/>
<ImageLinkForm
onInputChange={this.onInputChange}
onSubmit={this.onSubmit}
/>
<FaceRecognition
imageUrl={imageUrl}
/>
<FaceComparison
results = {results}
/>
</div>
: (
route === 'SignIn'
? <SignIn onRouteChange={this.onRouteChange}/>
: <Register />
)
}
</div>
);
};
}
export default App;
Rank.js
import React from 'react';
const Rank = ({results}) => {
const prediction = results.map((result) => {
const {ingredients} = result;
return (
<div>
<li className="celebrityName">{ingredients}</li>
</div>
);
});
if (prediction && prediction.length>1) {
return (
<div>
<div className='white f3'>
You look a lot like...
</div>
<div className='white f1'>
{results}
</div>
</div>
);
} else {
return (
<div>
</div>
)
}
};
export default Rank;
I have two pages on my react app. One page allows you to submit a post, and the second page shows all of the posts. I need to be able to retrieve the data from the state on one page, but I am receiving an error. What am I doing wrong to display this, because I thought I could use props to gather the state from my post page.
My Display Post Page:
import React from 'react';
import './App.css';
export default class Scroll extends React.Component {
render() {
return (
<div className="flex-container">
<div className="post">
{this.props.displayPost(this.props.state.posts)}
</div>
</div>
);
}
}
My post page:
import React from 'react';
import axios from 'axios';
import './App.css';
import { post } from '../../routes/routes';
export default class PersonList extends React.Component {
state = {
title: "",
body: "",
posts: []
};
componentDidMount = () => {
this.getPost();
}
getPost = () => {
axios.get("http://localhost:5000/posts/save")
.then((response) => {
const data = response.data;
this.setState({ posts: data });
console.log("Data has been recieved")
})
.catch(() => {
alert("Error recieving data")
})
}
handleChange = (event) => {
const target = event.target;
const name = target.name;
const value = target.value;
this.setState({
[name]: value
})
};
submit = (event) => {
event.preventDefault();
const payload = {
title: this.state.title,
body: this.state.body,
}
axios({
url: 'http://localhost:5000/posts/save',
method: 'POST',
data: payload,
})
.then(() => {
console.log('Data sent to the server');
})
.catch(() => {
console.log('Internal server error');
});
};
displayPost = (posts) => {
if (!post.length) return null;
return posts.map((post, index) => {
<div key={index}>
<h3 id="post-text">{post.title}</h3>
<p id="post-text">{post.body}</p>
</div>
});
}
render() {
console.log("State ", this.state)
return (
<div className="flex-container-home">
<div className="app">
<form onSubmit={this.submit}>
<input
placeholder="title"
type="text"
name="title"
value={this.state.title}
onChange={this.handleChange}
/>
<textarea placeholder="description"
name="body"
cols="30" rows="10"
value={this.state.body}
onChange={this.handleChange}
>
</textarea>
<button>Submit</button>
</form>
</div>
</div>
)
}
}
Here is working example:
import React from "react";
export default class PersonList extends React.Component {
state = {
title: "",
body: "",
posts: [],
};
componentDidMount = () => {
this.getPost();
};
getPost = () => {
this.setState({ posts: ["post1", "post2", "post3"] });
};
displayPost = (posts) => {
if (!posts || !posts.length) return null;
return posts.map((post, index) => (
<div key={index}>
<p>{post}</p>
</div>
));
};
render() {
return (
<div className="App">
<Scroll displayPost={this.displayPost} posts={this.state.posts} />
</div>
);
}
}
class Scroll extends React.Component {
render() {
return (
<div className="post">
Posts: {this.props.displayPost(this.props.posts)}
</div>
);
}
}
I'm trying to add the notable residents's names listed for every planet that is clicked using this API: https://swapi.dev/
I tried doing it at the bottom of the Planet detail page, but it is not working.
The notable residents are links to other API resources, and I don't know how to deal with them.
ERROR:
TypeError: Cannot read property 'map' of undefined
PlanetDetail.render
C:/Users/charl/Desktop/IRONHACK/Paperbox/paperbox/src/pages/Planetdetail.js:75
72 | )}
73 | </div>
74 | <div>
> 75 | <h1>Notable people</h1>
| ^ 76 | {
77 | this.state.planetInfo.residents.map(resident =>
78 | <p>{resident.name}</p>
HOME.JS
import React, { PureComponent } from 'react'
import axios from "axios";
import {Link} from "react-router-dom"
class Home extends PureComponent {
constructor(props) {
super(props)
this.state = {
planets: [],
filteredPlanets: []
}
this.handleChange = this.handleChange.bind(this)
}
handleChange(e){ // eslint-disable-next-line
let planetssearchlist = this.state.planets.filter(planet => {
if(planet.name){
if(planet.name.toLowerCase().includes(e.target.value.toLowerCase())){
return true
}
}
})
this.setState({
filteredPlanets: planetssearchlist
})
}
componentDidMount(){
axios({
method: "GET",
url: "https://swapi.dev/api/planets/"
})
.then(response => {
console.log(response.data.results)
let planetslist = response.data.results;
this.setState({planets: planetslist, filteredPlanets: planetslist})
})
.catch(error => {
console.log("You've made an error with the planets load charles: ",error)
})
}
render() {
return (
<div>
<h1>Star Wars Planets</h1>
<form>
<input placeholder="searchbar" type="text" onChange={this.handleChange}></input>
</form>
{
this.state.filteredPlanets.map((planet,i) => (
<Link to={{ pathname: "/info", state:{planet:planet} }}><p key={i}>{planet.name}</p></Link>
))
}
</div>
)
}
}
export default Home
PLANETDETAIL.JS
import React, { PureComponent } from "react";
import axios from "axios";
class PlanetDetail extends PureComponent {
constructor(props) {
super(props)
this.state = {
url: "",
planetInfo: {},
isGettingPlanetInfo: false
};
}
getPlanetInfo = () => {
this.setState({
isGettingPlanetInfo: true
});
axios({
method: "GET",
url: this.state.url
})
.then(response => {
console.log(response.data);
this.setState({
planetInfo: response.data,
isGettingPlanetInfo: false
});
})
.catch(error => {
this.setState({
isGettingPlanetInfo: false
});
console.log(
"You've made an error with the planet detail load charles: ",error
);
});
};
componentDidMount = () => {
this.setState(
{
url: this.props.location.state.planet.url
},
this.getPlanetInfo
);
};
render() {
return (
<div>
<div>
{this.state.isGettingPlanetInfo ?
(<p>Getting planet info...</p>) :
typeof this.state.planetInfo === "object" && Object.keys(this.state.planetInfo).length ?
(
<div>
<h1>Planet details</h1>
<p>planet name: {this.state.planetInfo.name}</p>
<p>rotation period: {this.state.planetInfo.rotation_period}</p>
<p>orbital period: {this.state.planetInfo.orbital_period}</p>
<p>diameter: {this.state.planetInfo.diameter}</p>
<p>climate: {this.state.planetInfo.climate}</p>
<p>gravity: {this.state.planetInfo.gravity}</p>
<p>terrain: {this.state.planetInfo.terrain}</p>
<p>surface water: {this.state.planetInfo.surface_water}</p>
<p>population: {this.state.planetInfo.population}</p>
</div>
) : (
""
)}
</div>
<div>
<h1>Notable people</h1>
{
this.state.planetInfo.residents.map(resident =>
<p>{resident.url}</p>
)
}
</div>
</div>
);
}
}
export default PlanetDetail
Since you're using state to set the url to fetch for planet details, planetInfo won't be populated in your initial render. You're already guarding against this for the other planet info, so do the same for the residents section by putting it under the same conditional.
You need to actually fetch the resident details – they aren't part of the planet response. I'd abstract that into a new component. Here's a Codepen of such a component.
render() {
return (
<div>
<div>
{this.state.isGettingPlanetInfo ? (
<p>Getting planet info...</p>
) : typeof this.state.planetInfo === "object" &&
Object.keys(this.state.planetInfo).length ? (
<>
<div>
<h1>Planet details</h1>
<p>planet name: {this.state.planetInfo.name}</p>
<p>rotation period: {this.state.planetInfo.rotation_period}</p>
<p>orbital period: {this.state.planetInfo.orbital_period}</p>
<p>diameter: {this.state.planetInfo.diameter}</p>
<p>climate: {this.state.planetInfo.climate}</p>
<p>gravity: {this.state.planetInfo.gravity}</p>
<p>terrain: {this.state.planetInfo.terrain}</p>
<p>surface water: {this.state.planetInfo.surface_water}</p>
<p>population: {this.state.planetInfo.population}</p>
</div>
<div>
<h1>Notable people</h1>;
{
this.state.planetInfo.residents.map(<Resident url={resident} />);
}
</div>
</>
) : (
""
)}
</div>
</div>
);
}
// Resident.js
const Resident = ({ url }) => {
const [resident, setResident] = React.useState(null);
React.useEffect(() => {
const fetchResident = async () => {
try {
const response = await axios({
method: "GET",
url
});
setResident(response.data);
} catch (error) {
console.error("Error retrieving resident", error);
}
};
fetchResident();
}, [url]);
return resident ? (
<div>
<span>{resident.name}</span>
</div>
) : (
<div>Fetching resident...</div>
);
};
I am trying to pass a pass down id from getUsers() to a child component as a prop.
App.jsx
import React, { Component } from 'react';
import { Route, Switch } from 'react-router-dom';
import axios from 'axios';
import About from './components/About';
import NavBar from './components/NavBar';
import Form from './components/forms/Form';
import Logout from './components/Logout';
import UserStatus from './components/UserStatus';
import Seeds from './components/Seeds';
import Message from './components/Message';
class App extends Component {
constructor() {
super();
this.state = {
users: [],
title: 'Project',
isAuthenticated: false,
messageName: null,
messageType: null,
restaurant: '',
email: '',
id: '',
username: '',
active: '',
admin: '',
};
this.logoutUser = this.logoutUser.bind(this);
this.loginUser = this.loginUser.bind(this);
this.createMessage = this.createMessage.bind(this);
this.removeMessage = this.removeMessage.bind(this);
this.userStatus = this.userStatus.bind(this);
};
componentWillMount() {
if (window.localStorage.getItem('authToken')) {
this.setState({ isAuthenticated: true });
};
};
componentDidMount() {
this.getUsers();
this.userStatus();
};
getUsers() {
axios.get(`${process.env.REACT_APP_WEB_SERVICE_URL}/users`)
.then((res) => { this.setState({ users: res.data.data.users }); })
.catch((err) => { });
};
logoutUser() {
window.localStorage.clear();
this.setState({ isAuthenticated: false });
};
loginUser(token) {
window.localStorage.setItem('authToken', token);
this.setState({ isAuthenticated: true });
this.getUsers();
this.createMessage('Welcome', 'success');
};
userStatus(event) {
const options = {
url: `${process.env.REACT_APP_WEB_SERVICE_URL}/auth/status`,
method: 'get',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${window.localStorage.authToken}`
}
};
return axios(options)
.then((res) => {
console.log(res.data)
console.log(res.data.data)
this.setState({
restaurant: res.data.data.restaurant,
email: res.data.data.email,
id: res.data.data.id,
username: res.data.data.username,
active: String(res.data.data.active),
admin: String(res.data.data.admin),
})
})
.catch((error) => { console.log(error); });
};
createMessage(name='Sanity Check', type='success') {
this.setState({
messageName: name,
messageType: type
});
setTimeout(() => {
this.removeMessage();
}, 3000);
};
removeMessage() {
this.setState({
messageName: null,
messageType: null
});
};
render() {
return (
<div>
<NavBar
title={this.state.title}
isAuthenticated={this.state.isAuthenticated}
/>
<section className="section">
<div className="container">
{this.state.messageName && this.state.messageType &&
<Message
messageName={this.state.messageName}
messageType={this.state.messageType}
removeMessage={this.removeMessage}
/>
}
<div className="columns">
<div className="column is-half">
<br/>
<Switch>
<Route exact path='/' render={() => (
<SpotifyAuth
/>
)} />
<Route exact path='/about' component={About}/>
<Route exact path='/register' render={() => (
<Form
formType={'Register'}
isAuthenticated={this.state.isAuthenticated}
loginUser={this.loginUser}
createMessage={this.createMessage}
/>
)} />
<Route exact path='/login' render={() => (
<Form
formType={'Login'}
isAuthenticated={this.state.isAuthenticated}
loginUser={this.loginUser}
createMessage={this.createMessage}
/>
)} />
<Route exact path='/logout' render={() => (
<Logout
logoutUser={this.logoutUser}
isAuthenticated={this.state.isAuthenticated}
/>
)} />
<Route exact path='/status' render={() => (
<UserStatus
isAuthenticated={this.state.isAuthenticated}
/>
)} />
<Route exact path='/seeds' render={() => (
<Seeds
isAuthenticated={this.state.isAuthenticated}
userStatus={this.userStatus}
/>
)} />
</Switch>
</div>
</div>
</div>
</section>
</div>
)
}
};
export default App;
Seeds.jsx
import React, { Component } from 'react';
import axios from 'axios';
class Seeds extends Component{
constructor (props) {
super(props);
this.state = {
restaurant:'',
email: '',
id: '',
username: '',
active: '',
admin: '',
template:'',
formSeeds:{
type1:'',
type2:'',
type3:'',
},
formEditMenu:{
item:'',
item2:'',
item3:'',
}
};
this.handleChange = this.handleChange.bind(this);
this.handleSubmitSeeds = this.handleSubmitSeeds.bind(this);
this.handleSubmitItems = this.handleSubmitItems.bind(this);
};
componentDidMount() {
if (this.props.isAuthenticated) {
this.getSeeds();
}
};
getSeeds(event) {
const {userStatus} = this.props
const options = {
url: `${process.env.REACT_APP_WEB_SERVICE_URL}/seeds/${userStatus.id}`,
method: 'get',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${window.localStorage.authToken}`
}
};
return axios(options)
.then((res) => {
console.log(res.data.data)
this.setState({
restaurant: res.data.data[0].restaurant,
id: res.data.data[0].id,
template: res.data.data[0].content
})
console.log(userStatus.id);
})
.catch((error) => { console.log(error); });
};
handleChange(event){
const objformSeeds = this.state.formSeeds;
objformSeeds[event.target.name] = event.target.value;
this.setState(objformSeeds);
const formEditMenu = this.state.formEditMenu;
formEditMenu[event.target.name] = event.target.value;
this.setState(formEditMenu);
}
handleSubmitSeeds(event) {
event.preventDefault();
const {userStatus} = this.props
const data = {
type1: this.state.formSeeds.type1,
type2: this.state.formSeeds.type2,
type3: this.state.formSeeds.type3,
};
const url = `${process.env.REACT_APP_WEB_SERVICE_URL}/handle_seeds/${userStatus.id}`;
axios.post(url, data)
.then((res) => {
console.log(data);
})
.catch((err) => {
});
};
handleSubmitCoffees(event) {
event.preventDefault();
const {userStatus} = this.props
const data = {
item: this.state.formEditMenu.item,
item2: this.state.formEditMenu.items2,
items3: this.state.formEditMenu.items3,
};
const url = `${process.env.REACT_APP_WEB_SERVICE_URL}/edit_menu/${userStatus.id}`;
axios.post(url, data)
.then((res) => {
console.log(data);
})
.catch((err) => {
});
};
render(){
var __html = this.state.template;
var template = { __html: __html };
return (
<div id="parent">
<div dangerouslySetInnerHTML={template}/>
<form>
<input type='text' name='name' onChange={this.handleChange}/><br/>
<button type="button" onClick={this.handleSubmitItems} />
</form>
</div>
);
}
}
export default Seeds;
but I'm getting userStatus undefined.
XHR failed loading: GET "http://localhost/seeds/undefined".
console.log(userStatus):
userStatus(event) {
const options = {
url: "".concat("http://localhost", "/auth/status"),
method: 'get',
headers: {
'Content-Type': 'application/json',
Authoriza…
what am I missing?
I would recommend you pass down the id only because you using this.userStatus is the function
userStatus={this.userStatus}
You need to change to
userStatus={this.state.id}
I am new to react programming. It might be silly mistake but, i can't access state data in my smart component.
Following is my code.
import React, { Component } from 'react';
class App extends Component {
constructor() {
super();
this.state = {
resData: [],
}
}
componentDidMount() {
fetch(`http://someurl.com/something`)
.then(response => response.json())
.then(result => { alert(result.data[0].title); this.setState({ resData: result.data }));
}
render() {
return (
<div>
<Header />
<ErrorBoundary>
<Content data={ this.state.resData } />
</ErrorBoundary>
<Footer />
</div>
);
}
export default App;
If i alert data in following then it was there.
.then(result => { alert(result.data[0].title) setState({ resData: result.data })); //Here i can see my data.
I want to pass this state data to my component. But, there are no data.
<Content data={ this.state.resData } />
Any help would be greatly appreciated.
Try now:
You need to use this keyword with setState()
import React, { Component } from 'react';
class App extends Component {
constructor() {
super();
this.state = {
resData: [],
}
}
componentDidMount() {
fetch(`http://someurl.com/something`)
.then(function (response) {
return response.json()
})
.then(function (result) {
this.setState({ resData: result.data })
})
.catch(function (error) {
alert("Username password do not match")
})
}
render() {
const { resData } = this.state;
return (
<div>
{resData &&
<Header />
<ErrorBoundary>
<Content data={resData} />
</ErrorBoundary>
<Footer />
}
</div>
);
}
export default App;
Check it now
The alert is running before the setState is finishing, try running the alert as a callback to setState:
componentDidMount() {
fetch(`http://someurl.com/something`)
.then(response => response.json())
.then(result => this.setState({ resData: result.data }), () => {
alert(this.state.resData);
});
}
try this it might help
import React, { Component } from 'react';
class App extends Component {
constructor() {
super();
this.state = {
resData: [],
}
}
componentDidMount() {
var that = this;
fetch(`http://someurl.com/something`)
.then(response => response.json())
.then(result => { alert(result.data[0].title); that.setState({ resData: result.data }));
alert(that.state.resData);
}
render() {
var that = this;
return (
<div>
<Header />
<ErrorBoundary>
<Content data={ that.state.resData } />
</ErrorBoundary>
<Footer />
</div>
);
}
export default App;