when i add that console.log(3); to the class below it throws error
class AlbumList extends Component {
state ={ albums: [] };
console.log(3);
componentWillMount() {
console.log(4);
axios.get('https://rallycoding.herokuapp.com/api/music_albums')
.then(response => this.setState({ albums: response.data }));
}
renderAlbums() {
console.log(5);
return this.state.albums.map(
album => <AlbumDetail key={album.title} myAlbum={album} />
);
}
render() {
console.log(6);
return (
<View>
{this.renderAlbums()}
</View>
);
}
}
You need to put console.log(3) inside any method, example you can add it on componentDidMount()
componentDidMount() {
console.log(3)
}
Related
I am new at react and
I have been trying to apply event handling in react but facing some Problem on onclick event.
When the button "show me of germany" is called the Page then stuck to loading only ...
Here is the code i have written ..
class App extends Component {
constructor(props) {
super(props);
this.state = { articles: [],
isLoaded:false ,
country:'us'
}
this.change = this.change.bind(this);
}
componentDidMount() {
const APIurl = `https://newsapi.org/v2/top-headlines?country=${this.state.country}&apiKey=${API_KEY}`;
fetch(APIurl)
.then(response => response.json())
.then(json => {
this.setState({
articles: json.articles,
isLoaded:true
})
})
}
// function to change the state
change()
{
this.setState({
articles: [],
isLoaded:false ,
country:"de"
})
}
render() {
const { isLoaded,articles } = this.state;
if(!isLoaded)
{
return (<h1>Loading....</h1>)
}
return (
<div>
<Navbar/>
<button onClick={this.change}>show me of germany</button>
<ul>
{articles.map(item=>(
<News item={item}/>
))}
</ul>
</div>
);
}
}
export default App;
Hope you understood the problem
You have to do request again.
class App extends Component {
constructor(props) {
super(props);
this.state = {
articles: [],
isLoaded: false,
country:'us'
}
this.change = this.change.bind(this);
}
componentDidMount() {
fetchData(this.state.country);
}
componentDidUpdate(prevProps, prevState) {
const { country: prevCountry } = prevState;
const { country: nextCountry } = this.state;
if (prevCountry !== nextCountry) {
fetchData(nextCountry);
}
}
change() {
this.setState({ country: 'de' });
}
fetchData(country) {
this.setState({ articles: [], isLoaded: false });
fetch(
`https://newsapi.org/v2/top-headlines?country=${country}&apiKey=${API_KEY}`
)
.then(res => res.json())
.then(({ articles }) => {
this.setState({ articles, isLoaded: true });
})
.catch(console.error);
}
render() {
//...
}
}
export default App;
I need help to display the data from the API.
When i try to get the data with map i get an error. TypeError: userdata.map is not a function
import React from "react";
import axios from "axios";
export class HighscoreList extends React.Component {
constructor(props) {
super(props);
this.state = {
users: ""
};
}
componentDidMount() {
axios
.get("https://schnitzeljagdar.herokuapp.com/users/getAllUser")
.then(response => {
console.log(response.data);
})
.catch(error => {
console.log(error);
});
}
render() {
return (
<React.Fragment>
<h2>User</h2>
{this.state.users}
</React.Fragment>
);
}
}
Try this https://codesandbox.io/s/wonderful-cherry-63ee9
export default class HighscoreList extends React.Component {
state = {
users: []
};
componentDidMount() {
axios
.get("https://schnitzeljagdar.herokuapp.com/users/getAllUser")
.then(res => this.setState({users:[res.data]}))
.catch(error => {
console.log(error);
});
}
render() {
const {users} = this.state;
let array = users[0]?Object.values(users[0]):[];
console.log(array)
return (
<React.Fragment>
{array.map((arr,index)=>
<div key={index}>
<h2>{arr.username}</h2>
<p>{arr.email}</p>
</div>
)}
</React.Fragment>
);
}
}
beneath is my code
class Root extends React.Component {
constructor(props) {
super(props);
this.state = {
data: [],
}
}
componentDidMount() {
this.getDataFromDb();
}
getDataFromDb = () => {
fetch('http://localhost:3001/getData')
.then((data) => data.json())
.then((res) => {
if(res !== this.state.data) {
this.setState({ data: res}, () => console.log(this.state.data));
}
});
};
render() {
return(
<div>
<IRPage data={this.state.data}></IRPage>
</div>
)
}
}
class IRPage extends Component {
print = () => {
console.log(this.props.data);
}
render() {
return (
<div className="container m-5">
<button onClick={this.print}></button>
</div>
)
}
}
callback function of setstate in getDatafromDB in Root component work successfully,
but when it pass to child component IRPage, and click print button, result is undefined.
Thank you for helping
You code seems to work as you intended it.
I tried to replicate what you wrote and it's working. checkout this jsfiddle
class Root extends React.Component {
constructor(props) {
super(props);
this.state = {
data: [],
}
}
componentDidMount() {
this.getDataFromDb();
}
getDataFromDb = () => {
fetch('https://jsonplaceholder.typicode.com/todos/1')
.then((data) => data.json())
.then((res) => {
if(res !== this.state.data) {
this.setState({ data: res}, () => console.log(this.state.data));
}
});
};
render() {
return(
<div>
<IRPage data={this.state.data}></IRPage>
</div>
)
}
}
// here I have added React to import Components from, because I don't know what import statement is
class IRPage extends React.Component {
print = () => {
console.log(this.props.data);
}
render() {
return (
<div className="container m-5">
<button onClick={this.print}></button>
</div>
)
}
}
ReactDOM.render(<Root />, document.querySelector("#app"))
I have some code that works. It immediately reroutes a user from the /test page to the FinishedPaying page. It is as so:
class Test extends Component {
renderRedirect = () => {
return <Redirect to="/FinishedPaying" />;
};
componentDidMount() {
this.renderRedirect();
}
...
The following code is meant to send a Paypal transaction, then route the user to the /FinishedPaying page. All of the other logic is working as expected:
export default class Pay extends React.Component {
state = {
userInput: ""
};
renderRedirect = () => {
return (
<Redirect
to="/FinishedPaying"
userInput={this.state.userInput}
/>
);
};
componentDidMount() {
this.setState({ userInput: this.props.userInput });
this.renderRedirect();
}
render() {
const onSuccess = payment => {
axios
.post(
"http://amazonaws.com:3000/ethhash",
{
userInput: this.props.userInput,
}
)
.then(response => console.log(response.data, payment))
.catch(function(error) {
console.log(error);
});
};
return (
<div>
<PaypalExpressBtn
onSuccess={onSuccess}
/>
</div>
);
}
}
Not sure why the second code block is working. It is my understanding that this.renderRedirect() should fire after all of the other logic has happened. It does not seem to be firing at all. Any feedback is appreciated :)
you can put it in your render like:
render() {
if (this.state.redirect){
return <Redirect
to="/FinishedPaying"
userInput={this.state.userInput}
/>;
}
const onSuccess = payment => {...}
As soon as you change your redirect value in state for true you will be redirected.
You can't return the component <Redirect to="/FinishedPaying" /> in componentDidMount, you can only do that in render().
You could have a flag that sets to true when you're ready to redirect:
componentDidMount() {
this.setState({
userInput: this.props.userInput,
readyToRedirect: true
});
}
Then in your render method:
render() {
this.state.readyToRedirect
? <Redirect to="/FinishedPaying" />
: other stuffs...
or in my opinion, a more readable way:
render() {
if (this.state.readyToRedirect) return <Redirect to="/FinishedPaying" />
return (
// rest of the code
)
I also wouldn't define onSuccess function inside render, every state change will trigger render and re-define the function again and again.
If it doesn't require anything from this, you can even put it outside of the class
const onSuccess = payment => {
...
}
export default class Pay extends React.Component {
...
}
export default class Pay extends React.Component {
state = {
redirect: false
};
renderRedirect = () => {
if(this.state.redirect){
return (
<Redirect
to="/FinishedPaying"
userInput={this.props.userInput}
/>
);
}
};
componentDidMount() {
this.setState({ redirect: true });
}
render() {
const onSuccess = payment => {
axios
.post(
"http://amazonaws.com:3000/ethhash",
{
userInput: this.props.userInput,
}
)
.then(response => console.log(response.data, payment))
.catch(function(error) {
console.log(error);
});
};
return (
<div>
{this.renderRedirect()}
<PaypalExpressBtn
onSuccess={onSuccess}
/>
</div>
);
}
}
I'm using a callback from axios.get to set the state of a React component. The data property of the response contains an array of objects which I use to set state.
When I log the state property to the console there are no issues and I can see the array of objects. However if I try to log one of those objects individually I get the error:
Cannot read property '0' of null at ResponsiveTable.render
Below is the code for my component:
class ResponsiveTable extends React.Component {
constructor (props) {
super(props)
this.state = {
returnedQuery: null
};
}
componentDidMount() {
axios.get('/api/latestLeads')
.then((response) => {
this.setState({
returnedQuery: response.data
});
})
.catch(function (error) {
console.log(error);
});
}
render() {
console.log(this.state.returnedQuery[0]);
return (
<div>
<h1>test</h1>
</div>
);
}
}
Sure at first render your returnedQuery is null so you are getting this error.
If you want to use this.state.returnedQuery[0] check if it's exist and it's length > 0:
render() {
if (this.state.returnedQuery && this.state.returnedQuery.lenth > 0){
return (
<div>
{this.state.returnedQuery.map(...)}
</div>
);
} else {
return <div>loading data...</div>
}
}
You could try this:
class ResponsiveTable extends React.Component {
constructor (props) {
super(props)
this.state = {
returnedQuery: null
};
this.getData();
}
getData = () => {
axios.get('/api/latestLeads')
.then((response) => {
this.setState({
returnedQuery: response.data
}, () => {console.log(this.state.returnedQuery);}); //What does this console.log() say?
})
.catch(function (error) {
console.log(error);
});
}
render() {
console.log(this.state.returnedQuery[0]);
return (
<div>
<h1>test</h1>
</div>
);
}
}
I found the solution which was quite similar to Andrew's above, I used the component's internal state to determine whether the axios.get method had returned. Below is the working code, I'm now able to access elements within the returned array and their properties.
class ResponsiveTable extends React.Component {
constructor (props) {
super(props)
this.state = {
returnedQuery: null
};
}
componentDidMount() {
const self = this;
// let returnedQuery;
axios.get('/api/latestLeads')
.then((response) => {
self.setState({
returnedQuery: response.data
});
console.log(response.data);
})
.catch(function (error) {
console.log(error);
});
}
render() {
return (
<div>
<h1>{'This will always render'}</h1>
{ this.state && this.state.returnedQuery &&
<div>{this.state.returnedQuery[0].email}</div>
}
</div>
)
}
}