Home > Blockchain >  Cannot read properties of undefined (reading 'length') in codesandbox
Cannot read properties of undefined (reading 'length') in codesandbox

Time:05-26

const News = (props)=>{
    const [articles, setArticles] = useState([])
    const [loading, setLoading] = useState(true)
    const [page, setPage] = useState(1)
    const [totalResults, setTotalResults] = useState(0)
    
    const capitalizeFirstLetter = (string) => {
        return string.charAt(0).toUpperCase()   string.slice(1);
    } 

    const updateNews = async ()=> {
        props.setProgress(10);
        const url = `https://newsapi.org/v2/top-headlines?country=${props.country}&category=${props.category}&apiKey=${props.apiKey}&page=${page}&pageSize=${props.pageSize}`; 
        setLoading(true)
        let data = await fetch(url);
        props.setProgress(30);
        let parsedData = await data.json()
        props.setProgress(70);
        setArticles(parsedData.articles)
        setTotalResults(parsedData.totalResults)
        setLoading(false)
        props.setProgress(100);
    }

    useEffect(() => {
        document.title = `${capitalizeFirstLetter(props.category)} - NewsPanda`;
        updateNews(); 
        // eslint-disable-next-line
    }, [])


    const fetchMoreData = async () => {   
        const url = `https://newsapi.org/v2/top-headlines?country=${props.country}&category=${props.category}&apiKey=${props.apiKey}&page=${page 1}&pageSize=${props.pageSize}`;
        setPage(page 1) 
        let data = await fetch(url);
        let parsedData = await data.json()
        setArticles(articles.concat(parsedData.articles))`enter code here`
        setTotalResults(parsedData.totalResults)
      };
 
        return (
            <>
                <h1 className="text-center" style={{ margin: '35px 0px', marginTop: '90px' }}>NewsPanda - Top {capitalizeFirstLetter(props.category)} Headlines</h1>
                {loading && <Spinner />}
                <InfiniteScroll
                    dataLength={articles.length} /////here i'm getting this error/////
                    next={fetchMoreData}
                    hasMore={articles.length !== totalResults}
                    loader={<Spinner/>}
                > 
                    <div className="container">
                         
                    <div className="row">
                        {articles.map((element) => {
                            return <div className="col-md-4" key={element.url}>
                                <NewsItem title={element.title ? element.title : ""} description={element.description ? element.description : ""} imageUrl={element.urlToImage} newsUrl={element.url} author={element.author} date={element.publishedAt} source={element.source.name} />
                            </div>
                        })}
                    </div>
                    </div> 
                </InfiniteScroll>
            </>
        )
    
}

while forking my code from github to codesandbox its shoeing error "Cannot read properties of undefined (reading 'length') in codesandbox" . but i have defined articles above .I really don't know what is happening here . anyone got solution for this . its showing error at line dataLength = {articles.length};

CodePudding user response:

In code an object has to be defined.

In your code articles probably not defined thus length cannot be resolved.

{ articles.length ...

Two things you need to do is see that articles indeed properly set as an array. And you can add a validation for articles variable

{ articles?.length

The validation can lead to other errors so you better validate your variables as early in your code as you can.

CodePudding user response:

You are receiving an error as a response from newsapi.org

{
  code: "corsNotAllowed"
  message: "Requests from the browser are not allowed on the Developer 
  plan, except from localhost."
  status: "error"
}

Your News component is expecting articles to be an array and breaks if it is not. You should only add parsedData.articles into state conditionally, or else it could be undefined.

  const updateNews = async () => {
    setError(null)
    props.setProgress(10);
    const url = `https://newsapi.org/v2/top-headlines?country=${props.country}&category=${props.category}&apiKey=${props.apiKey}&page=${page}&pageSize=${props.pageSize}`;
    setLoading(true);
    let data = await fetch(url);
    props.setProgress(30);
    let parsedData = await data.json();

    if (parsedData.status !== 'error') {
      props.setProgress(70);
      setArticles(parsedData.articles);
      setTotalResults(parsedData.totalResults);
      props.setProgress(100);
    } else {
      props.setProgress(0);
      setError('Something went wrong')
    }
    setLoading(false);
  };

Edit morning-pond-1ur0ey

  • Related