reactjsreact-hooksaxiostwitch-api

data.map is not a function when trying to fetch api from twitch


I am building a simple fan made page for a streamer using felix twitch api . 2 days now i cant get around with a problem im facing when trying to display fetched data to front end . My code is as follows.

 import React, { useState, useEffect } from "react";
 import axios from 'axios';
 
 
 export const Home = () => {
 
   const [loading, setLoading] = useState(true);
   const [data, setData] = useState([])
 
   const client_id = "3fjsnq21qnimeiel9b773vwbhmjurk";
   const token = "5z79quc5s7z0qbiiqmalqd4ueh4lue";
   const url = "https://api.twitch.tv/helix/clips?broadcaster_id=42365125"
 
   const requestOptions = {
     method: "GET",
     headers: {
       "client-id": client_id,
       Authorization: "Bearer " + token,
     },
   };
 
   useEffect(() => {
     const fetchData = async () =>{
       setLoading(true);
       try {
         const {data: response} = await axios.get(url,requestOptions);
         setData(response.data);
         console.log(response.data)
 
       } catch (error) {
         console.error(error.message);
       }
       setLoading(false);
     }
 
 
     fetchData();
     console.log(data);
   }, []);
 
 
 
 
     return (
       <div>
         hi
       {loading && <div>Loading</div>}
       {!loading && (
         <div>
           <h2>Doing stuff with data</h2>
           {data.map(item => (<span>{item.id}</span>))}
         </div>
       )}
       </div>
     );
   
 };

What I'm trying to do here is to create an array of the data twitch returns. Which in Cli mode returns an object and inside of it and array . Then with the function map to go trhough all videos of the streamer in order to display them in my front end. Thats the console in chrome with the code above.

Check chrome console image here


Solution

  • In API response there is no need to stringify the data which is set in setData state.... There is no need when use axios to stringify the data

    useEffect(() => {
     const fetchData = async () =>{
       setLoading(true);
       try {
         const {data: response} = await axios.get(url,requestOptions);
         setData(response.data);
         console.log(response.data)
    
       } catch (error) {
         console.error(error.message);
       }
       setLoading(false);
     }
    
     fetchData();
     console.log(data);
    }, []);