2

Making my first project in react but getting console printed twice.

import axios from 'axios';
export default function App() {


  const [searchText ,setSearchText]=useState("");
  console.log(searchText); 


  //api key

  function searchForOrder(){
    //set up correct api call
    var APICall= `http://lookup-app.teflon.order-services.com/orders-lookup/services/v4/orders?orderNo=${searchText}`;
    console.log(APICall)
    //handle api call
    axios.get(APICall)
      .then(function (response) {
        //success  
        console.log(JSON.parse(response.data));
      })
      .catch(function (error) {
        console.log(error);
      });
  }

  return (
    <div className='template'>
      <div className='search'>
          <div className='form-control'>
            <label htmlFor='number'>Search your order Number</label>
            <input
              type='name'
              name='OrderNo'
              id='OrderNo'
              value={searchText}
              onChange={e => setSearchText(e.target.value)}
            />
            <button onClick={searchForOrder} className='submit'>search</button>
          </div>
      </div>
    </div>
  )
}

My console looks like this: every number getting printed two times

Can somebody please let me know where I am going wrong because , I haven't worked in reactJs before. Thanks in advance!

1 Answer 1

2

This is caused by the re-rendering of components, React renders each components multiple time, Call console.log inside of useEffect hook and pass the searchText vaiable inside the useEffect dependency array.

Example:

useEffect(() => {
console.log(searchText); ;
}, [searchText]); 

P.s: Don't forget to import useEffect from react before using it.

Sign up to request clarification or add additional context in comments.

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.