Hello everyone i have a problem with my code! with useContext
here is my Request to Server:
import axios from "axios";
export const SearchForTracks = async (entValue, tokens) =>{
const response = await axios.get(`https://api.spotify.com/v1/searcq=${entValue}&type=artist`{
headers:{
'Authorization': `Bearer ${tokens}`
}
})
return response.data.artists.items
}
and it's the Response i got from my request, it geives me an array of objects like this:
(19) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]
and here is my changeHandler Function and useState, i want to get artists from request and pass them throw useContext to another Component
export const ArtistContext = createContext();
function TopSearch() {
const [open, setOpen] = useState(false); // Open State
const [tokens] = useContext(TokenContext) // tokens Context
const [artists,setArtists] = useState([]) // Artists State
// onChange Handler for Search
const onChangeHandler = async(event) =>{
[event.target.name] = event.target.value; // set value to input
let entValue = event.target.value;
setArtists(SearchForTracks(entValue,tokens)); // Send input Value to API and get response back
}
return (
<>
<ArtistContext.Provider value={artists}>
{open ?
<SearchLanding />
:
null
}
</ArtistContext.Provider>
</>
);
}
export default TopSearch;
so when i pass data to my child Component i receive data like this:
Promise {<pending>}
[[Prototype]]
:
Promise
[[PromiseState]]
:
"fulfilled"
[[PromiseResult]]
:
Array(19)
so when i want to destruct this and get data or map() on them i can't do this, it says .map() is not a function or it returnes undefined.
so what is the solution?
SearchForTracks
is a Promise. You have to await it.
setArtists(await SearchForTracks(entValue,tokens));