DevoJo
DevoJo

Reputation: 11

How can I get the value of an input field and use it in URL in React

I have to complete this project and I'm having a hard time understanding how the hooks work. I'm completely new to React and I was wondering how I could grab the value of my Input field so I could use it and modify the URL of the API (omdb) I'm working with. ( see ${inputValue} )

Here's the code:

function App() {
  const [searchResult, setSearchResult] = useState()


  useEffect(() => {
    const search = async () => {


      const response = await fetch(
        `http://www.omdbapi.com/?apikey=aaaaaa&s=${inputValue}`,
      )

      const data = await response.json()
      console.log(data);

      if (!searchResult) {
        setSearchResult(data);

      }
    }

    search()
  })

  return (
    <div className="App">
      <div className="search">
        <input type="text" placeholder="Search..." />
        <button>Search</button>
      </div>
      {!searchResult ? (
        <p>No results yet</p>
      ) : (
          <div className="search-results">
            <div className="chevron">
              <ChevronLeft />
            </div>
            <div className="search-results-list">
              {searchResult.Search.map(result => (
                <div key={result.imdbID} className="search-item">
                  <img
                    src={result.Poster === 'N/A' ? placeholderImg : result.Poster}
                    alt="poster"
                  />
                  <div className="search-item-data">
                    <div className="title">{result.Title}</div>
                    <div className="meta">{`${result.Type} | ${result.Year}`}</div>
                  </div>
                </div>
              ))}
            </div>
            <div className="chevron">
              <ChevronRight />
            </div>
          </div>
        )}
    </div>
  )
}

It seemed very simple at first, I thought I could just querySelect the Input tag's value but for some reason that didn't work. I've been searching around but nothing seems to work and very method I tried returns "undefined".

Thanks for the help!!

Upvotes: 1

Views: 1140

Answers (2)

Viet
Viet

Reputation: 12787

You can use define inputValue as a state:

  const [inputValue, setInputValue] = useState("");

Assign value to inputValue, and onChange callback you need to set value to inputValue:

      <input
        type="text"
        value={inputValue}
        onChange={(e) => {
          setInputValue(e.target.value);
        }}
      />

Minimal working sample: https://codesandbox.io/s/stoic-bell-j3e2p?file=/src/App.js:180-328

Upvotes: 0

AdriSolid
AdriSolid

Reputation: 2825

First, set a state for yout input value:

const [inputVal, setVal] = useState('');

Then, add value and onChange to your input:

<input type="text" placeholder="Search..." value={inputVal} onChange={onInputChange} />

Create a function to set the input value to the state

function onInputChange(evt) {
  setVal(e.target.value);
}

Use you input state value as a dependency array of your useEffect

useEffect(() => {
  const search = async (value) => {
    const response = await fetch(
      `http://www.omdbapi.com/?apikey=a461e386&s=${value}`,
    );

    const data = await response.json();

    if (!searchResult) {
      setSearchResult(data);
    }
  }

  if (inputVal) {
    search(inputVal);
  }
}, [inputVal])

Upvotes: 0

Related Questions