Home > Enterprise >  The result shows in console log but not on the page when using useRef & useCallback in react
The result shows in console log but not on the page when using useRef & useCallback in react

Time:04-20

I know extracting data from API is asynchronous and the state would not be available at such time, So we are supposed to use useCallBack, but even though the Data logged successfully but not shows on the webpage.

This is what I did.

const HomePage = (props: any) => {
    const news = props.listNews; // used useCallBack and the data got from the API and logged successfully

    const trending: MainNewsData[] = [];

    const trendingRef = useRef<MainNewsData[]>([]);

    const getNews = useCallback(() => {

        for (let i = 0; i < news.length; i  ) {
            const e = news[i];
            if (e.category_title === 'Trending') trending.push(e);
            maxHeap.insert(e);
        }
        trendingRef.current = [...trending];

        console.log("trendingRef", trendingRef) // logged successfully
    }, [trendingRef]);

    useEffect(() => {
        getNews();
    }, [getNews]);

    return (
        <>
            {< TrendingNews className={''} currentTrendingNews={trendingRef.current.slice(0, 6)} />}
        </>
    );
};

export default HomePage;

I don't want to use the filter function because I have 8 categories, So using the filter function 8 times is expensive.

I appreciate any answer.

CodePudding user response:

setting a ref will not rerender the component. try using useState instead.

const HomePage = (props: any) => {
    const news = props.listNews; // used useCallBack and the data got from the API and logged successfully

    const trending: MainNewsData[] = []; 

    const [trendingState, setTrendingState] = useState([])

    const getNews = useCallback(() => {
        for (let i = 0; i < news.length; i  ) {
            const e = news[i];
            if (e.category_title === 'Trending') trending.push(e);
            maxHeap.insert(e);
        }
        setTrendingState([...trending]);

        console.log("trendingState", trendingState) // logged successfully
    }, []);

    useEffect(() => {
        getNews();
    }, [getNews]);

    return (
        <>
            {< TrendingNews className={''} currentTrendingNews={trendingState.slice(0, 6)} />}
        </>
    );
};

export default HomePage;
  • Related