Search code examples
reactjsapiuse-effect

How can I get this simple API fetch call work?


I am a new React developer. trying to use hooks to call on an API and show the data on screen(after that will try to mess with pagination and filtering results) however for some reason the fetch call does not work , It would work when I show it in Postman but not in my app

***main state***

const [apiData, setApiData] = useState({})

***my use Effect hook***

useEffect(() => {

async function getMusicData(){
const music = await fetch('theaudiodb.com/api/v1/json/523532/searchalbum.php?s=daft_punk')
.then(res => res.json())
setApiData(music)
console.log(apiData)
}
console.log(apiData)
getMusicData()
},[])

***my rendering attempt***

return (
<Router>
<Navbar />
{dataApi.map((s, i) => (

))}
</Router>
);

again(I get a red squiggly under the brackets also!)showing the red squiggly:

Showing API call results in postman

console.log(apiData/music) gets me this also

Let me know if I can provide you with anything more, I am trying to understand why it wouldn't work in the first place! appreciate your response


Solution

  • firstly your url is wrong. Your fetch url should have https

    https://theaudiodb.com/api/v1/json/523532/searchalbum.php?s=daft_punk
    

    so, if you use async keyword this mean fetch will work asynchronous so you dont need then() function.

    You should like this

     const music = await fetch(
        "https://theaudiodb.com/api/v1/json/523532/searchalbum.php?s=daft_punk"
      );
      const response = await music.json();
    

    then you should use your setApiData()

      setApiData(response);
    

    if you add console.log(apiData) here you cant see anything. Because your setApiData() function is asynchronous so, you can see it at next render.

    I get a red squiggly under the brackets also!

    I think, it's about the spacing between parentheses. You should add html element (div,span,etc...)

    Finally, i fix your code. You can check it.

    export default function App() {
      const [apiData, setApiData] = useState([]);
    
      useEffect(() => {
        async function getMusicData() {
          const music = await fetch(
            "https://theaudiodb.com/api/v1/json/523532/searchalbum.php?s=daft_punk"
          );
          const response = await music.json();
    
          setApiData(response.album);
        }
       
        getMusicData();
      }, []);
    
      return (
        <div className="App">
          {apiData.map((s) => (
            <div key={s.idAlbum}>{s.strAlbum}</div>
          ))}
        </div>
      );
    }
    

    https://codesandbox.io/s/elegant-rgb-3zzo3f?file=/src/App.js:395-401