score:0
you can store the value of input field inside state and use it directly inside async call.
plus you need a onchange handler as every time you update input text, state should know the updted value.
import react from 'react';
import './app.css';
class app extends react.component {
constructor(props) {
super(props);
// here.........................
this.state = { apiresponse: '', text : null };
}
// here ...........................
handlechnage = (e) => this.setstate({text : e.target.value})
async callapi() {
// checking the input value and pass to api..................
console.log(this.state.text)
const ipaddress = '8.8.8.8';
const api_url = `http://localhost:9000/ipdata/${ipaddress}`;
const res = await fetch(api_url, {
headers: {
'content-type': 'application/json',
accept: 'application/json',
},
});
const json = await res.json();
console.log(json);
// don't use it..............use state to pass the data
document.getelementbyid('city').textcontent = json.city;
document.getelementbyid('state').textcontent = json.region_code;
document.getelementbyid('zip').textcontent = json.zip;
}
render() {
// here on input element .................
return (
<div classname="app">
<h1>ip search</h1>
<input type="text" value={this.state.text} onchange={this.handlechange}></input>
<button onclick={this.callapi}>search ip</button>
<p>
<span id="city" /> <span id="state" /> <span id="zip" />
</p>
</div>
);
}
}
export default app;
note - don't use imperative methods like getelementbyid and others in react.
score:0
please avoid using dom methods in reactjs, here is an example of what you might want to do with your application. `
import react,{usestate} from 'react';
function app(){
const [apires,setapires]= usestate('');
const [loading,setloadng]= usestate(false);
const callapi= async()=>{
// supose this is your api response in json
const hello={
city:"city1",
region_code:"region#123",
zip:"00000"
}
// loading while city and zip are not available
setloadng(true)
await settimeout(()=>{setapires(hello)},5000)
}
return (
<div classname="app">
<h1>ip search</h1>
<input type="text"></input>
<button onclick={callapi}>search ip</button>
{!apires && loading && <p>loading count till 5...</p>}
<p>
{apires &&
(
<>
<span> {apires.city}</span>
<span> {apires.region_code}</span>
<span> {apires.zip}</span>
</>
)}
</p>
</div>
);
}
export default app;
` link to sandbox: [sandbox]: https://codesandbox.io/s/priceless-mclaren-y7d7f?file=/src/app.js/ "click here to run above code"
score:1
there are two issues:
to get the input value, use a controlled component: put the input value into state and add a change handler.
to set the
city
,state
,zip
sections, don't use vanilla dom methods (which should be avoided in react in 95% of situations) - instead, put the response into state.
class app extends react.component {
constructor(props) {
super(props);
this.state = { apiresponse: '', inputvalue: '', result: {} };
}
async callapi() {
try {
const api_url = `http://localhost:9000/ipdata/${this.state.inputvalue}`;
const res = await fetch(api_url, {
headers: {
'content-type': 'application/json',
accept: 'application/json',
},
});
const result = await res.json();
this.setstate({ result });
} catch (error) {
// handle errors - don't forget this part
}
}
render() {
return (
<div classname="app">
<h1>ip search</h1>
<input
type="text"
value={this.state.inputvalue}
onchange={e => this.setstate({ inputvalue: e.target.value })}
/>
<button onclick={this.callapi}>search ip</button>
<p>
<span>{this.state.result.city}</span>
<span>{this.state.result.state}</span>
<span>{this.state.result.zip}</span>
</p>
</div>
);
}
}
Source: stackoverflow.com
Related Query
- React passing data into Async Function from Input
- passing data from child to parent component - react - via callback function
- Passing data from one function to another in React
- Use data from async function on React State with JSX
- Passing data from an Asp.Net view into a React Component
- How do I load API data into input value property on page load from React State?
- How to get data from an async function in React
- Passing data into component from React Router
- Accessing data from an async function in React and Typescript
- Passing Data from React Table to a Input TextField Material ui
- Passing info from a Form into a function React js
- React JS passing data from firebase into props for my component
- React - Updating parameters for function calls by taking data from one component and passing it to the next is lagging by one step
- Is there a way to get input data from createElement() function in React
- Passing initial data from the server into React application
- loading json data from local file into React JS
- Is there a right way to pass data into a React component from the HTML page?
- How can I get data from a local file into my React app?
- How to get form data from input fields in React
- React - load all data from json into component
- Passing Data from Child to Parents React Hooks
- Passing an empty function into a React component
- React: How to add onChange functionality inside of Function component using React Hooks? Need onClick event from a checkbox to influence input state
- React Apollo first object from subscription not being merge into previous data it actually gets removed
- React - How to pass returned data from an exported function to a component?
- Passing API data from parent container to child component in React
- Passing data from rails controller to react component
- React - Passing fetched data from API as props to components
- Passing data from same level components React
- Refresh a React Child Functional Component based on Async input from Parent
More Query from same tag
- Unable to toggle expanded nav menu
- How to create a common component for reducing similar separate components creation in ReactJS?
- Next.js setting click event only on Image component
- Undefined object when sending a JSON object from Express server into React?
- Which is the correct way to Get & Set data (not state/props) without re-render React component?
- React - input checkbox onchange won't fire first time
- React-grid-layout - drag only on first div
- React/Typescript : this.setState is not a function
- Calling useState inside useEffect on DOM load
- Next.js PDFtron Webviewer - ReferenceError: window is not defined
- Getting referrence error while creating new array of object from existing array of objects?
- Using SwipeableViews with updateHeight()
- Load Specific Tab Component in React
- Validation input full name
- React class prop onclick
- htaccess with two indexes for locales
- State not clearing when the amout of component has changed
- Can't access e.target.name
- how to display a div with multiple conditions in reactjs
- How to compare object key as array value and assign a value to the variable?
- React not updating text (issue with .getDOMNode())
- The next.js image is transparent
- redux flow is giving error
- Create dynamic initial states for React useContext
- Changing logo in gatsby theme
- How to dispatch the received values?
- How to add external JS on index.html in React boilerplate?
- display a component in button click (using hooks)
- How do you render nested SASS in webpack?
- how to append object array to current state in react functional component