I created a simple date picker react js, after that I call API and get some data from API in the console, now I want to fetch API data on the web page.
Here is the code i used to call API function, I want map response data on a web page
import React, { Component } from 'react' import axios from 'axios' class PostForm extends Component { constructor(props) { super(props) this.state = { key: '', } console.log(this.state) } changeHandler = e => { this.setState({ [e.target.name]: e.target.value }) } submitHandler = e => { e.preventDefault() axios .get(`http://127.0.0.1:8000/hvals_hash?key=${this.state.key}`) .then(response => { console.log(response.data) }) .catch(error => { console.log(error) }) } render() { const { key } = this.state return ( <center><div> <form onSubmit={this.submitHandler}> <div> <h2> DATE PICKER</h2><br></br> <input type="text" name="key" value={key} onChange={this.changeHandler} /> </div> <br></br> <button type="submit">Submit</button> </form> </div></center> ) } } export default PostForm
Advertisement
Answer
Here is the explanation for this issue you can refer here,
import React, { Component } from 'react' import axios from 'axios' class PostForm extends Component { constructor(props) { super(props) this.state = { key: '', // Where data will be saved. data: [], } console.log(this.state) } changeHandler = e => { this.setState({ [e.target.name]: e.target.value }) } submitHandler = e => { e.preventDefault() axios .get(`http://127.0.0.1:8000/hvals_hash?key=${this.state.key}`) .then(response => { // Updating the state to trigger a re-render this.setState({data: response.data}); console.log(response.data) }) .catch(error => { console.log(error) }) } render() { const { key } = this.state return ( <center><div> <form onSubmit={this.submitHandler}> <div> <h2> DATE PICKER</h2><br></br> <input type="text" name="key" value={key} onChange={this.changeHandler} /> </div> <br></br> <button type="submit">Submit</button> </form> <div> {this.state.data.map((dataObjectToDisplay) => { return ( <div> { <ol>{this.state.data}</ol> } </div> ); })} </div> </div></center> ) } } export default PostForm
add a state (add an object property to this.state) and inside the submit handler, after getting the response in Axios, use setState({[name of state]: response.data }).
That takes care of updating the state. As for where to display them, it is up to you.
You can copy the code anywhere inside the render method. If u want to display it under the form, paste it inside the div container after the form.
For better controlling of the state, you can check one of the state-management tools like redux or simply use global context and implement routing using react-router –
Credits to @MrCeRaYA