Print console.log/alert on React Component - reactjs

I'm trying to display data from an Event using Laravel into a React Component. While testing with console.log or alert, the message displays correctly as I wish. But being the noob that I'm, I don't know how to display the new event's data like I'm displaying the table's data using axios in the example bellow.
Like displaying the infos IN the component rather than externally using alert or console.log. Tried return and it didn't work.
React component :
import React,{Component} from 'react';
import axios from 'axios';
import { Link } from 'react-router-dom';
import Echo from "laravel-echo";
class Patient extends React.Component {
constructor(props) {
super(props)
this.state = {
patients : []
};
}
componentDidMount() {
axios.get('api/patients')
.then(response => {this.setState({patients: response.data})})
.catch(err => console.log(err));
window.Echo.channel('home')
.listen('NewPatient', (data) => {
alert(JSON.stringify(data));
}, (e) => {
alert(data);})
}
render() {
return (
<div>
<ul>
{ this.state.patients.map(patient => <li>{patient.nom}</li>)}
</ul>
</div>
)
}
}
export default Patient;
I want to display the data of this event in an HTML list, so each time there is a new output the list updates itself.
window.Echo.channel('home')
.listen('NewPatient', (data) => {
alert(JSON.stringify(data));
}, (e) => {
alert(data);})

Try set state:
window.Echo.channel('home')
.listen('NewPatient', newPatientData => {
this.setState({
patients: this.state.patients.concat(newPatientData)
})
}, e => {
console.log("Error", e)
})

Related

ReactJS - Data does not load in dropdown list from axios call

I have a React Component like below:
import axios from "axios";
import React from "react";
export default class PersonList extends React.Component {
state = {
users: [],
};
componentDidMount() {
axios
.get("https://jsonplaceholder.typicode.com/users")
.then((response) => {
// handle success
let thedata = response.data;
this.setState({ thedata });
console.log(thedata);
})
.catch((error) => {
// handle error
console.log(error);
});
}
render() {
return (
<select>
{this.state.users.map((user) => (
<option value={user.id}>{user.name}</option>
))}
</select>
);
}
}
The data shows up on console just fine. But my dropdown stills shows empty. No error whatsoever. What I am missing here?
You are setting state as {thedata:thedata} instead of {users:thedata}. Change it like so :-
componentDidMount() {
axios
.get("https://jsonplaceholder.typicode.com/users")
.then((response) => {
// handle success
let thedata = response.data;
this.setState({users:thedata });
console.log(thedata);
})
.catch((error) => {
// handle error
console.log(error);
});
}

React HOC with Router not finding page

Hi I am working on a react app with Routing and HOC. I expect to see a page but i get page not found when i know the page is there.
in componentDidMount this.setState, data is shown as undefined but in the HOC wrapper i see the data arrive from the server.
Before I wrapped the page in HOC i could see it rendering content so I know the content exists.
Here is my Page component which is being called via a Route :
import React, { Component } from "react";
import WithBackend from "./WithBackend";
class Page extends Component {
constructor(props) {
super(props);
this.state = { model: null };
}
render() {
if (this.state.model != null) {
return (
<div className="container">
<div className="row">
<div className="col-md">
<h1>{this.state.model.title}</h1>
</div>
</div>
</div>
);
} else {
return (
<div>
<h2>Home</h2>
</div>
);
}
}
componentDidMount() {
const data = this.props.getPage("1");
console.log(data);
this.setState({
model: data,
});
}
}
export default WithBackend(Page);
Here is the HOC component WithBackend: I am not sure if i should be setting the state on this class on in the class that is being wrapped.
When i debug the code in the getPage method, in the setState part i see the data being populated from the backend server.
import React from "react";
import ContentService from "./ContentService";
const WithBackend = (WrappedComponent) => {
class HOC extends React.Component {
constructor() {
super();
this.contentService = new ContentService();
this.getPage = this.getPage.bind(this); // <-- Add this
}
getPage(id) {
this.contentService
.getPage(id)
.then((response) => response.json())
.then((data) => {
this.setState({ model: data });
})
.catch((e) => {
console.log(e);
});
}
render() {
return <WrappedComponent getPage={this.getPage} {...this.props} />;
}
}
return HOC;
};
export default WithBackend;
and here is the contentService which only returns a promise:
class ContentService {
pageUrl = process.env.REACT_APP_BASE_URL + "/pages/";
getPage(id) {
const path = this.pageUrl + id;
const fetchPromise = fetch(path, {
method: "GET",
});
return Promise.resolve(fetchPromise);
}
}
export default ContentService;
Could anyone please advice what i am doing wrong?
Thanks in advance.
getPage is an asynchronous method, that should return a promise:
getPage(id) {
return this.contentService
.getPage(id)
.then((response) => response.json())
.catch((e) => {
console.log(e);
});
}
And then
componentDidMount() {
this.props.getPage("1").then(model => this.setState({ model }));
}

React Native Function ReferenceError

New to React Native here... I'm trying to call a function that does a get request inside a component which is in the render() method.
import React from 'react';
import { StyleSheet, Text, View, Button } from 'react-native';
export default class Home extends React.Component {
static navigationOptions = {
title: 'Details',
};
getMoviesFromApiAsync = () => {
return fetch('https://facebook.github.io/react-native/movies.json')
.then((response) => response.json())
.then((responseJson) => {
return responseJson.movies;
})
.catch((error) => {
console.error(error);
});
};
render() {
return (
<React.Fragment>
<Text>{getMoviesFromApiAsync()}</Text>
</React.Fragment>
);
}
}
However, I'm getting ReferenceError: Can't find variable getMoviesFromApiAsync(). Why is this?
Error Image
You need to call the method on your class, this is a basic Vanilla Javascript thing.
<Text>{this.getMoviesFromApiAsync()}</Text>
However, your approach here is not good, you should write the component out to store the results from your api request in component state. this way you dont need to make a request every render cycle!
export default class Home extends React.Component {
static navigationOptions = {
title: 'Details',
};
state = {
movies: []
}
componentDidMount() {
this.getMoviesFromApiAsync()
}
getMoviesFromApiAsync = () => {
return fetch('https://facebook.github.io/react-native/movies.json')
.then((response) => response.json())
.then((responseJson) => {
this.setState({
movies: [...this.state.movies, ...responseJson.movies]
})
})
.catch((error) => {
console.error(error);
});
};
render() {
const { movies } = this.state
return (
<React.Fragment>
{ movies.map( (movie, i) => <Text>{movie.title}</Text> ) }
</React.Fragment>
);
}
}

How to use embedly in reactjs through api?

I im new in react js i have only 25 days of experience of reactjs and i am trying to fetch the data from url of embedly but i can not understand how to use it i am using the url which is ( https://api.github.com/users/hadley/orgs ) it is fetch the data correctly but i want to fetch the data from the embed.ly this is my page in react name is PostListItems.js
can any body help me thanks in advance.
Type isn't a field that is returned from Github's API.
import React from 'react';
import { render } from 'react-dom';
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
data: []
};
}
componentDidMount() {
fetch('https://api.github.com/users/hadley/orgs', {
method: 'GET',
})
.then((resp) => resp.json())
.then(data => {
this.setState({ data: data });
}).catch(error => {
console.log(error);
});
}
render() {
return <div>
{this.state.data.map((data, index) => {
return <div key={index}>{data.id}: {data.url}</div>
})}
</div>
}
}
render(<App />, document.getElementById('root'));

React: Http request response not displaying in render()

Can someone tell me what is wrong with my code below? I am making an HTTP request to Darksky API using 'superagent' and then trying to display the result in an h2 which isn't working. I tried logging it to console and it works perfectly but if I am trying to display it on the page it doesn't work. Could someone help me out pls, I am new to react and not sure what is going wrong.
import React, { Component } from "react";
import "./Body.css";
import Request from "superagent";
class Body extends Component {
constructor() {
super();
this.getData = this.getData.bind(this);
}
getData() {
var url = this.props.apiUrl;
Request.get(url)
.then(response => {
return(JSON.stringify(response.currently.summary));
})
.catch(error => {});
}
render() {
<div>
<h2>
{this.getData()}
</h2>
</div>
}
}
export default Body;
This is the other file where I am importing Body.js :-
import React, { Component } from "react";
import Body from "./Body";
import "./App.css";
class App extends Component {
render() {
return <Body
apiUrl="https://api.darksky.net/forecast/42a9693aecf45c358afbda0022c5cf65/28.5355,77.3910" />;
}
}
export default App;
You need to set your data in the state of the component, it fire new render:
constructor() {
super();
this.getData = this.getData.bind(this);
this.state = {data: {}}
}
componentDidMount() {
var url = this.props.apiUrl;
Request.get(url)
.then(response => this.setState({data: JSON.stringify(response.currently.summary)}))
.catch(error => {});
}
render(){
console.log("your data", this.state.data);
return <div>test</div>;
}
And work with this data with this.state.data.
I advise you to change getData() function to componentDidMount mehtod.
You should use a life cycle method(componentDidMount) with the use of state. It is recommended to make HTTP calls inside the componentDidMount() method.
constructor() {
super();
this.state = {
result: ''
};
}
componentDidMount(){
var url = this.props.apiUrl;
Request.get(url)
.then(response => {
this.setState({
result: JSON.stringify(response.currently.summary)
});
})
.catch(error => {});
}
render() {
<div>
<h2>
{this.state.result}
</h2>
</div>
}

Resources