Im trying to make it so that the joke will display only when the toggle button is 'ON'. Right now I have the joke displaying all the time and not sure where I should go from here. Should I be using useEffect and how?
import React from 'react';
import axios from "axios";
class Toggle extends React.Component {
constructor(props) {
super(props);
this.state = {isToggleOn: true};
this.jokes = "https://icanhazdadjoke.com/"
// This binding is necessary to make `this` work in the callback
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
this.setState(prevState => ({
isToggleOn: !prevState.isToggleOn
}));
}
async componentDidMount() {
const url = "https://icanhazdadjoke.com/"
let result = null;
try {
result = await axios.get(url, {
headers: {
Accept: "application/json"
}
})
} catch(e) {
console.log(e);
}
this.setState({jokes: result.data.joke});
}
render() {
return (
<div>
<button onClick={this.handleClick}>
{this.state.isToggleOn ? 'ON' : 'OFF'}
</button>
<p>
> This displays the joke and changes when page is refreashed
{this.state.jokes}
</p>
</div>
);
}
}
export default Toggle;
you can do it this way:
{this.state.isToggleOn && <p> {this.state.jokes} </p>
it only shows the joke when the toggle is on.
Related
[enter link description here][1]I am fetching API in react. I am able to see data in console but it is not appearing in JSX. I want to see Data id, name and value. But it is not appearing in browser.
[1]: https://codesandbox.io/s/late-thunder-456qp?file=/src/App.js
import React from 'react';
import axios from 'axios'
import './App.css';
class Main extends React.Component {
constructor(props) {
super(props)
this.state = {
users: [],
error: ''
}
}
componentDidMount(){
axios.get('https://jsonplaceholder.typicode.com/users')
.then( response => {
console.log(response);
this.setState({users: response.data})
})
.catch(error =>{
console.log(error);
})
}
render() {
const { users } = this.state
return (
<div>
<h2> Main Page</h2>
<p class="para-text"> Data from API</p>
{
users.length ?
users.map(post => <div key ={ users.id }> { users.name} </div>) : null
}
</div>
);
}
}
export default Main;
when mapping you named the key to your map as post and therefore when displaying them in jsx you must refer to that key
attached is a forked version of your sandbox https://codesandbox.io/s/late-thunder-456qp?file=/src/App.js
import "./styles.css";
import React from "react";
import axios from "axios";
class Main extends React.Component {
constructor(props) {
super(props);
this.state = {
users: [],
error: ""
};
}
componentDidMount() {
axios
.get("https://jsonplaceholder.typicode.com/users")
.then((response) => {
this.setState({ users: response.data });
})
.catch((error) => {
console.log(error);
});
}
render() {
const { users } = this.state;
return (
<div>
<h2> Main Page</h2>
<p class="para-text"> Data from API</p>
{users.length > 0
? users.map((post) => <div key={post.id}> {post.name} </div>)
: null}
</div>
);
}
}
export default Main;
I'm unable to update the state using the axios response in a class component. It works just fine with function based components. Could somebody please point out what is causing this issue. I'm new to react and tried most of the possible answers out there.
code :
import React, { Component } from "react";
import "./Table.css";
import { Button } from "./Button";
import { Table } from "react-bootstrap";
import axios from "axios";
import Example from "./Progress";
class Tables extends Component {
constructor(props) {
super(props);
this.state = {
submitted: false,
task_id: "",
};
this.handlesubmit = this.handlesubmit.bind(this);
}
handlesubmit(event) {
var self = this;
event.preventDefault();
axios({
method: "post",
url: "http://127.0.0.1:8000/api/test/",
data: {
project_name: "test",
},
}).then(function (response) {
console.log(response.data.task_id); //prints taskid (12345678)
self.setState({
task_id: response.data.task_id,
});
console.log(self.task_id); //prints undefined
});
this.setState({ submitted: true }); //works fine, state is set to true
console.log(this.task_id); //prints undefined
}
render() {
let modal;
let task_id = this.state.task_id;
let submitted = this.state.submitted;
if (submitted === true) {
modal = <Example pro="test" task={task_id} />;
}
return (
<div className="table-div">
<Button
buttonStyle="btn--secondary"
buttonSize="btn--small--opt"
onClick={this.handlesubmit}
>
test
</Button>
{modal}
</div>
);
}
}
export default Tables;
You should update your state inside then when the axios call succeeds:
handleSubmit(event) {
event.preventDefault();
axios({...})
.then((response) => {
this.setState({
task_id: response.data.task_id,
submitted: true
})
})
.catch((error) => { /* handle errors appropriately */ })
}
Then, inside your render method, make sure that both task_id and submitted have appropriate values before rendering the modal:
render() {
const { task_id, submitted } = this.state
const modal = submitted && task_id !== ""
? <Example pro="test" task={task_id} />
: null // don't render anything
return (
<div className="table-id">
<Button ...>test</Button>
{modal}
</div>
)
}
TLDR: How would i retrieve the console.log from the child component
after url has been submitted
I want to be able to get the response data from the child component after a url has been submitted. How would i be able to do this ?
In other words how i be able to fire the onClick function after a url has been submitted ?
code sandbox
https://codesandbox.io/s/cool-feather-fjkv6
Parent
import React, {Component} from 'react';
import logo from './logo.svg';
import './App.css';
import Child from './Child';
class Parent extends Component {
constructor(props){
super(props);
this.state = {
url:'',
outputUrl:''
}
}
onChange = (e) => {
e.preventDefault();
this.setState({
url: e.target.value
})
}
onSubmit = (e) => {
e.preventDefault();
console.log(this.state.url)
}
render(){
return (
<div className="App">
<form onSubmit={this.onSubmit}>
<input type="text" onChange={this.onChange} value={this.state.url} placeholder="Enter url " />
<button type="submit" >Submit</button>
</form>
{/* if have url else enter test url */}
<Child url={this.state.url} method={'GET'} />
</div>
);
}
}
export default App;
How would i retrieve the console.log from the child component after url has been submitted ? I'm slightly confused. Sorry if this is looks confusing.
Child
import React, {Component} from 'react';
import logo from './logo.svg';
import './App.css';
import axios from 'axios';
class Child extends Component {
constructor(props){
super(props);
this.state = {
data:[]
}
}
// componentDidUpdate or try this
onClick(){
const url = `${this.props.url}`;
if(this.props.method === "GET"){
axios.get(url).then( res => {
this.setState({
data: res.data
})
console.log(this.state.data)
})
}
else if(this.props.method === "POST"){
axios.get(url).then( res => {
this.setState({
data: res.data
})
console.log(this.state.data)
})
}
}
render(){
return (
null
);
}
}
export default Child;
Please! see render method on Child Component
class Child extends Component {
static onClick() {
// do something
}
constructor(props) {
super(props);
this.state = {
data: []
};
}
// componentDidUpdate or try this
onClick = e => {
e.preventDefault();
const url = `${this.props.url}`;
if (this.props.method === "GET") {
axios.get(url).then(res => {
this.setState({
data: res.data
});
console.log(this.state.data);
});
} else if (this.props.method === "POST") {
axios.get(url).then(res => {
this.setState({
data: res.data
});
console.log(this.state.data);
});
}
};
render() {
return <div onClick={this.onClick}>Click Me</div>;// <------
}
}
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>
}
I am currently developing my first reactjs app and am having difficulties navigating from a Search component to a Results component using react-router-dom.
The search component accepts entries from the user, performs a get request with axios and updates its results state.
import axios from 'axios';
import React, {Component} from 'react';
import {Button} from 'react-bootstrap';
import Results from './Results';
class Search extends Component {
constructor(props) {
super(props);
this.state = {
results: [],
term: '',
};
this.submit = this.submit.bind(this);
this.changeTerm = this.changeTerm.bind(this);
}
changeTerm(event) {
this.setState({term: event.target.value});
}
submit(event) {
let url = 'http://api.example.com/results?q=' + encodeURI(this.state.term) + '&json=1';
axios.get(url)
.then(response => {
let data = {
results: response.data,
};
this.setState(data);
})
.catch(error => console.log(error));
}
render() {
return (
<div>
<form onSubmit={this.submit}>
<input onChange={this.changeTerm}/>
<Button type="submit" bsStyle="primary">Find</Button>
</form>
<Results data={this.state.results}/>
</div>
);
}
}
export default Search;
The results are currently displayed directly beneath the search component, but I would like to redirect the results to a new page with a different url. Both pages have to be different, because they have completely different structures and styles and must point to different urls.
Is it possible to forward the results from the Search component to the Results Component using react router? I am also open to other solutions which are not based on react router.
Have you checked out the Redirect component? Here's a basic idea (without actually testing it) that should get you started. You'll obviously have to add some more code to get it working.
class Search extends Component {
constructor(props) {
super(props);
this.state = {
results: [],
term: '',
};
this.submit = this.submit.bind(this);
this.changeTerm = this.changeTerm.bind(this);
}
changeTerm(event) {
this.setState({term: event.target.value});
}
submit(event) {
let url = 'http://api.example.com/results?q=' + encodeURI(this.state.term) + '&json=1';
axios.get(url)
.then(response => {
let data = {
results: response.data,
};
this.setState(data);
})
.catch(error => console.log(error));
}
render() {
return (
<div>
<form onSubmit={this.submit}>
<input onChange={this.changeTerm}/>
<Button type="submit" bsStyle="primary">Find</Button>
</form>
{this.state.results.length > 0 &&
<Redirect to={{
pathname: '/results',
state: { results: this.state.results }
}}/>
}
</div>
);
}
}
export default Search;
I used the same code but result data is not redirecting to search result page. i added below in the result.js
{this.state.results.id}