0

So, I'm trying to pass data from an input element into an async function within my React App.js file. I'm having trouble understanding how to push the input value into the callAPI function.

At the moment I just have a dummy/placeholder ipaddress within the callAPI inorder to test the button is working and calling the function onClick. Here's my code..

import React from 'react';
import './App.css';

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = { apiResponse: '' };
  }

  async callAPI() {
    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);
    document.getElementById('city').textContent = json.city;
    document.getElementById('state').textContent = json.region_code;
    document.getElementById('zip').textContent = json.zip;
  }

  render() {
    return (
      <div className="App">
        <h1>IP Search</h1>
        <input type="text"></input>
        <button onClick={this.callAPI}>Search IP</button>
        <p>
          <span id="city" /> <span id="state" /> <span id="zip" />
        </p>
      </div>
    );
  }
}

export default App;

3 Answers 3

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>
        );
    }
}
Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

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"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.