I'm using the Listen Notes podcast-api in Next.js api routes. I want the user query from my front-end form to interact with the Next.js api. So when a user inputs "history", it will send that to the api to look for podcasts that are about that topic. I tried adding params to axios request but that doesn't seem to work.
Front-end:
export default function SearchBar() {
const [query, setQuery] = useState("");
const [address, setAddress] = useState("");
const fetcher = async (url) => await axios.get(url, { params: {q: query } }).then((res) => res.data);
const { data, error } = useSWR(address, fetcher);
const handleSubmit = (e) => {
setAddress(`/api/podcast`);
e.preventDefault();
};
return (
<>
<Form onSubmit={handleSubmit}>
<Input
onChange={(e) => setQuery(e.target.value)}
/>
<SearchButton type="submit">Search</SearchButton>
</Form>
</>
);
}
Api code:
const { Client } = require("podcast-api");
export default function handler(req, res) {
const client = Client({
apiKey: process.env.REACT_APP_API_KEY || null,
});
//"q" below should contain the user query from front-end
client
.search({ q: req.params })
.then((response) => {
res.status(200).json(response.data);
})
.catch((error) => {
console.log("apiError: " error);
});
}
Please let me know if I need to provide more information.
CodePudding user response:
Check if API on you NextJs app, is receiving correctly the environment variable process.env.REACT_APP_API_KEY. Use console.log to test.
Reference : https://nextjs.org/docs/basic-features/environment-variables
Another check is the API path, cause NextJs use your own method to path this, you know ?!
Reference : https://nextjs.org/docs/api-routes/introduction
Hope this tips help you ;)
CodePudding user response:
The problem was in the api route, it should be:
.search({ q: req.query.q })
req.params is something else on server side and that's why it wasn't coming through.