0

I have developed this live search component in react which retrieves data from an API according to the input search value. However it doesn't retrieve or display the data when pointed to this API https://api.itbook.store/1.0/search/program

But when i use an API like for example: http://hn.algolia.com/api/v1/search?query=redux it retrieves data

  const [data, setData] = useState({ books: [] });
  const [query, setQuery] = useState('program');
  const [url, setUrl] = useState(
    'https://api.itbook.store/1.0/search/program',
  );

  useEffect(() => {
    const fetchData = async () => {
      const result = await axios(url);

      setData(result.data);
    };

    fetchData();
  }, [url]);

  return(
    <Paper className={classes.root}>

      <Container maxWidth="lg">

        <form className={classes.container} encType="multipart/form-data">

          <TextField
            required
            id="standard-required"
            placeholder="Enter Book Name"
            label="Search for a Book"
            name="bookName"
            value={query}
            onChange={event => setQuery(event.target.value)}
            className={classes.textField}
            multiline
            rowsMax="2"
          margin="normal"/>

          <Button onClick={() =>
            setUrl(`https://api.itbook.store/1.0/search/${query}`)
          }
            className={classes.button} color="primary">Search</Button>

          <ul>
            {data.books.map(item => (
              <li key={item.objectID}>
                <a href={item.url}>{item.title}</a>
              </li>
            ))}
          </ul>


        </form>

      </Container>

    </Paper>

I want my code to collect the data from the API Json : https://api.itbook.store/1.0/search/something

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
Carl
  • 483
  • 1
  • 3
  • 14
  • Dont you have to specify exactly what type of request you want to make with axios? Like axios.get(url) or axios.post(url, body)? – Chris Ngo Jul 05 '19 at 09:04
  • Look at your console. You will see this error: `...has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.` Then, you can search for this error. – devserkan Jul 05 '19 at 09:13
  • 1
    Possible duplicate of [XMLHttpRequest cannot load XXX No 'Access-Control-Allow-Origin' header](https://stackoverflow.com/questions/35553500/xmlhttprequest-cannot-load-xxx-no-access-control-allow-origin-header) – Quentin Jul 05 '19 at 09:30
  • @ChristopherNgo — No: https://github.com/axios/axios#axiosurl-config – Quentin Jul 05 '19 at 09:31

1 Answers1

3

@sideshowbarker delivers an excellent solution to this problem Trying to use fetch and pass in mode: no-cors

Essentially what you can do to workaround the CORS issue is make your request via CORS Proxy URL.

Here's a working sandbox with updates to your code: https://codesandbox.io/s/lucid-kapitsa-w1uid

import React, { useState } from "react";
import ReactDOM from "react-dom";
import axios from "axios";

import "./styles.css";

const App = () => {
  const [url, setUrl] = useState("https://api.itbook.store/1.0/search/");
  const [query, setQuery] = useState("");
  const [results, setResults] = useState([]);

  const fetchData = async () => {
    const proxyURL = "https://cors-anywhere.herokuapp.com/";
    const updatedURL = `${proxyURL}${url}${query}`;
    const res = await axios(updatedURL);

    setResults(res.data.books);
  };

  const createBookList = () => {
    return results.map(book => {
      return (
        <div>
          <h4>{book.title}</h4>
        </div>
      );
    });
  };

  return (
    <div>
      <input onChange={e => setQuery(e.target.value)} value={query} />
      <button onClick={fetchData}>Click</button>
      <div>{createBookList()}</div>
    </div>
  );
};
Chris Ngo
  • 15,460
  • 3
  • 23
  • 46