The rendered input is getting interpreted as word ‘object’ rather than text getting entered in input in React. So I have this API I want to search with input while I am searching it is getting written word ‘object’ rather than what am I writing.
Object is getting written instead of what I searched for
Here I searched for input but again object is getting written in query
import { useState } from "react";
function () {
const [endpoint, setEndpoint] = useState("");
function searchChange(e) {
setEndpoint(e.target.value);
console.log(endpoint);
const options = {
method: "GET",
headers: {
"X-RapidAPI-Key": "baef7285e6msh0aae02b3fd1dde5p1d01aajsne4c06de3d63f",
"X-RapidAPI-Host": "spotify81.p.rapidapi.com",
},
};
fetch(
"https://spotify81.p.rapidapi.com/search?q=" +
{endpoint} +
"&type=albums&offset=0&limit=10&numberOfTopResults=5",
options
)
.then((response) => response.json())
.then((response) => console.log(response))
.catch((err) => console.error(err));
}
return (
<input
className="input"
value={endpoint}
placeholder=" 🔍 Search"
onChange={searchChange}
/>
);
}
2
Answers
Your code is properly formated, but I noticed that how you build the url is probably incorrect.
Right now I look like you always send
q={endpoint}
as a string and no the variable.Try to change your fetch to this using string interpolation:
When building your fetch URL you add
+{endpoint}+
which will result in a string with aq
of[object Object]
The correct way to concatenate the fetch URL is the following, by removing the brackets
{}
Now this will fetch your
endpoint
but it will be one step (character) behind since setState is sort of async meaning yourendpoint
value inside thesearchChange
function will not get updated until the next render. You can fix this by directly using thee.target.value
inside your URL.Or using a
useEffect
for when theendpoint
value changesThis way you can use the
endpoint
value in your fetch.