简体   繁体   中英

Why is my React state undefined even after setting the state in UseEffect hook?

So this code is getting latitude and longitude passed down from a parent component and then fetching a country code and then fetching news articles based on that country code to pass down to a child. However, when I try to pass the data down I am getting "paper is undefined". Am I setting the state correctly?

import React, {useState, useEffect} from 'react';
import { usePosition } from 'use-position';
import Article from './Article';
import './App.css'


const News = (lat, lng) => {

    const API_KEY = `XXXXXXXXXXXXXXXXXXXXX`
    var url; 
    var newsurl;
    var country;
    const [paper, setPaper] = useState();        

    useEffect(() =>{
        if (typeof lat.lat !== "undefined" && typeof lat.lng !== "undefined"){
            url = `https://api.opencagedata.com/geocode/v1/json?q=${lat.lat}%2C${lat.lng}&key=${API_KEY}&pretty=1`
       }   
        async function getCountry(mUrl) {   
            const response = await fetch(mUrl);
            const countryData = await response.json();
            country = countryData.results[0].components["ISO_3166-1_alpha-2"];
            newsurl = `https://newsapi.org/v2/top-headlines?country=${country.toLowerCase()}&apiKey=XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX`;

            const response2 = await fetch(newsurl);
            const newsData = await response2.json();
            setPaper(newsData);
            //newsData.articles.map((article) => console.log(article.title));
        }

        getCountry(url);
    },[]);
console.log(paper)


return(
        <div>
           {paper.articles.map(article => (
               <Article name={article.title}/>
           )
           )}           

        </div>
    )
}

export default News;

The first render (before useEffect done) paper is undefined (because you setState without params). So set state like this:

 const [paper, setPaper] = useState(null);   

in the last return (render) try this:

 {paper && paper.articles.map(article => ( ....

or

 {paper ? paper.article.map(... : <WaitComponent/>

and rename input props lat, lng with coord and before define first url test:

 if (typeof coord.lat !== 'undefined' && typeof coord.lng !== 'undefined')          
{
  url = `https://api.opencagedata.com/geocode/v1/json?q=${coord.lat}%2C${coord.lng}&key=${API_KEY}&pretty=1`;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM