Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
170 views
in Technique[技术] by (71.8m points)

reactjs - React hooks component not updating after map, but see data loading / refreshing with error

I'm using React hooks and Typescript.

Basically, I'm grabbing data from an API through a service in useEffect, setting state through a .then(). When I log the data from this point, I can see it in the console, but the component is not updating. I'm an experienced dev but new to React completely.

Also, if I do something dumb like put {newsItems} in the return unwrapped once the data is loaded is will show an error. I'm guessing it is some simple mistake I am just blind to.

Here is the code:

import React, { Fragment, useContext, useEffect, useState } from 'react'
import { IFeedItem, IOwlerResponse, OwlerResponse } from '../../../../app/ models/owler'
import FeedItem from './FeedItem';



function formatOwlerResponse(response: any): OwlerResponse { 
    // console.log(response.feeds);
    return { feeds: response.feeds, pagination_id: response.pagination_Id }

}



class ItemService { 

    getItems(url: string): Promise<OwlerResponse> {
        return fetch(
            `https://api.owler.com/v1/feed/url?domain=${url}&format=json&limit=100`,
            {
              method: "GET",
              headers: new Headers({
                   (Redacted)

              })
            })
            .then(res => res.json())
           // .then(res => res.map((response: any) => formatOwlerResponse(response))
            .then(res => formatOwlerResponse(res))
          
            }} 




export const CompanyNewsFeed = () => {
    
    const [url, setUrl] = useState('google.com');
    const [newsItems , setNewsItems] = useState<IFeedItem[]>([])
    const [isLoading, setIsLoading] = useState(true); 
    const client = new ItemService()

    
    
    
    useEffect(()=>{
        client.getItems('google.com').then(r=> {
            console.log(r.feeds)
            setNewsItems(r.feeds); 
        })
        console.log('set')


    }, [url, formatOwlerResponse]);



    return (
        <Fragment>
                        
                 {newsItems.map(item =>{
                     <Fragment key={item.id}>
                        <h1>{item.title}</h1>
                        <p>{item.description}</p>

                     </Fragment>


                 })} 

        </Fragment>
            


        
       

    )
}

export default CompanyNewsFeed 

Update -> I made a button for forceUpdate() and refresh() when I hit those I got an error that said I might have more than one version of react installed, which would account for the odd behaviour, since I've seen tutorials mostly mapped out exactly like my application. I did have a moment where I was changing the dependences to take care of warnings and I was at various points on 16.8, 16.14, and 17.0.1 or 17.1. I had had Mobx in too, and I spent a day checking that that was setup correctly. Will update if that doesn't solve it.

question from:https://stackoverflow.com/questions/65651536/react-hooks-component-not-updating-after-map-but-see-data-loading-refreshing

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Just need to consider these

first you're adding [url, formatOwlerResponse] as useEffect dependency array so if none of the variables don't change so your api will only be called once.

another thing that you need to consider is that to check for newsItems length because your mapping through it and if it's not an array it would give you an error

return (
      <Fragment>
          { newsItems?.map(item =>{
              <Fragment key={item.id}>
                <h1>{item.title}</h1>
                <p>{item.description}</p>
              </Fragment>
          })} 
      </Fragment>
  )

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...