Home > database >  Change Axios baseURL dynamically according to user Input
Change Axios baseURL dynamically according to user Input

Time:06-03

I Would like to change the Axios base URL according to the userInput. I'm using the google books API and want to alter the search query (q=) based on whatever is entered in the inputbox.

I think this could be done by placing the baseURL inside a function and calling it onClick of the submit button.

const baseURL = `https://www.googleapis.com/books/v1/volumes?q={input}`;
export default function App() {
  
  const [post, setPost] = React.useState(null);
 
  React.useEffect(() => {
    axios.get(baseURL).then((response) => {
      setPost(response.data);
    });
  }, []);

  if (!post) return null;
  return (
    <>
    <input placeholder="bookname"></input> 
      <button>Submit</button>
      <h1>{post.items[0].volumeInfo.title}</h1>
      <h2>{post.items[0].volumeInfo.publisher}</h2>
      <img src={post.items[0].volumeInfo.imageLinks.thumbnail} />
    </>
  );
}

Thanks!

Edit snowy-cookies-fk9rf5

CodePudding user response:

You can maintain a state variable that can hold the input text. The url can be constructed dynamically using es6 template strings.

Edit laughing-sound-cod1ye

export default function App() {
  const [post, setPost] = React.useState(null);
  const [query, setQuery] = React.useState("themartian");

  async function getBooks() {
    const baseURL = `https://www.googleapis.com/books/v1/volumes?q=${query}`;
    const response = await axios.get(baseURL);
    setPost(response.data);
  }

  function onClick() {
    getBooks();
  }

  React.useEffect(() => {
    getBooks();
  }, []);
...

There is also an alternate approach using useRef as we don't really need a state variable to trigger a re-render every time on user input.

export default function App() {
  const [post, setPost] = React.useState(null);
  const inputRef = React.useRef(null);

  async function getBooks() {
    let query = "themartian";
    if (inputRef.current) {
      query = inputRef.current.value;
    }
    const url = `https://www.googleapis.com/books/v1/volumes?q=${query}`;
    const response = await axios.get(url);
    setPost(response.data);
  }

  function onClick() {
    getBooks();
  }

  React.useEffect(() => {
    getBooks();
  }, []);
...

Edit tender-greider-d9bjub

  • Related