reactjsaxiosgoogle-custom-search

Error while consuming the custom search engine google api


I have a ReactJs app with a search bar and i want to consume the API custom search engine of google and im having the following error:

"Request contains an invalid argument."

The docs of the API shows the following url:

https://customsearch.googleapis.com/customsearch/v1?key=[YOUR_API_KEY]

Im using the exact url but instead i paste my API_KEY without the brackets.

This is my reactjs component Search.js:

import axios from 'axios'
import Searchbar from '../molecules/Searchbar'
import { useState } from 'react';


const Search = () => {    
  
  const [searchText, setSearchText] = useState('');
  
  function searchInGoogle(e){
    
    const BASE_URL = `https://customsearch.googleapis.com/customsearch/v1`
    const API_KEY = process.env.REACT_APP_SEARCH_KEY;
    const SEARCH_ENGINE_KEY = process.env.REACT_APP_SEARCH_ENGINE_KEY;
    var apiCall = `${BASE_URL}?key=${API_KEY}&q=${searchText}`
    axios.get(apiCall).then(function (response){
      console.log(response)
    }).catch(function(error){
      console.log(error);
    })
    
  }

  const handleInputChange = (e) => {
    setSearchText(e.target.value)
  }
  
  console.log(searchText)

  return (
    <div>
      <input className='searchInput' onChange={handleInputChange} ></input>
      <button className='btn' onClick={searchInGoogle} >Submit</button>
      {/* <Searchbar /> */}
    </div>
  )
}

export default Search I tried both ways:

`${BASE_URL}?key=${API_KEY}&cx=${SEARCH_ENGINE_KEY}&q=${searchTerm}`

and

`${BASE_URL}?key=${API_KEY}&q=${searchTerm}`

In my console i get GEThttps://customsearch.googleapis.com/customsearch/v1?key=undefined&q=asd


Solution

  • In a project created by create-react-app, only env vars beginning with REACT_APP_ are defined in process.env.

    Change your .env file to include

    REACT_APP_SEARCH_KEY=xxxxx
    REACT_APP_SEARCH_ENGINE_KEY=xxxxx
    

    You should also use Axios' params config to correctly and safely encode query parameters. Eg

    // search.js
    import axios from "axios";
    
    const BASE_URL = "https://customsearch.googleapis.com/customsearch/v1";
    const API_KEY = process.env.REACT_APP_SEARCH_KEY;
    const SEARCH_ENGINE_KEY = process.env.REACT_APP_SEARCH_ENGINE_KEY;
    
    export const searchInGoogle = async (searchTerm) => {
      // don't forget `await`
      const { data } = await axios.get(BASE_URL, {
        params: {
          key: API_KEY,
          cx: SEARCH_ENGINE_KEY,
          q: searchTerm,
        },
      });
      return data;
    };
    
    import { useState } from "react";
    import { searchInGoogle } from "./search";
    
    const Search = () => {
      const [searchText, setSearchText] = useState("");
    
      const handleSubmit = (e) => {
        e.preventDefault();
    
        searchInGoogle(searchText).then(console.log).catch(console.error);
      };
    
      const handleInputChange = (e) => {
        setSearchText(e.target.value);
      };
    
      return (
        <div>
          <input className="searchInput" onChange={handleInputChange}></input>
          <button className="btn" onClick={searchInGoogle}>
            Submit
          </button>
        </div>
      );
    };