Search code examples
reactjsfetchstate

Setting a state in fetch call gives me undefined?


Hi im trying to set a state in my fetch call, When I try to access the state it returns undefined. Im not sure why it does this can someone help?


 var [articlearray, setArticle]= React.useState([]);
 
 var options = {
     method: 'POST',
     headers: {
         'Content-Type': 'application/json'
         },
         body: JSON.stringify({headline: props.headline})

     };

     
 fet(options)
        
 function fet(options){
     
     fetch('/headlines', options).then(response => response.json()).then(data =>{
     
        
          var newsData = data.newsArray

         

         setArticle(newsData)
        
        
       })
     
 }
console.log(articlearray[0]);


Solution

  • You could use useEffect to load all of your data from an API endpoint. The emtpy array [] on the useEffect means that it will run once, on the beginning of the lifecycle.

    var [articlearray, setArticle] = React.useState([]);
    
    const fetchData = async () => {
      var options = {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({
          headline: props.headline
        })
      };
    
      fetch('/headlines', options).then(response => response.json()).then(data => {
        var newsData = data.newsArray;
        setArticle(newsData);
        console.log(articlearray[0]);
      })
    }
    
    useEffect(() => {
      fetchData();
    }, []);