reactjsswr

useSWR, component's state is not updating to the resolved promise of fetcher


Here is my code

// service
import axios from 'axios';
export const fetchNewsDetailsById = (newsID) => {
    console.log('args in fetch news ', newsID)
    const pr = axios.get('https://swapi.dev/api/people/1')
    .then(res => res.data)
    .then(res => {
        const X = res.data.filter(obj => obj.id == newsID)[0];
        console.log('api data ', X);
        //// THIS X I WANT IN MY COMPONENT
        return X;
    });
    console.log('my promise ', pr);
    return pr;
}



// hook
import useSWR from 'swr'
import { fetchNewsDetailsById } from './service';

export const useNewsDetailsBySlug =  (newSlug) => {
    const parts = newSlug.split("-");
    const newsId = parts[parts.length - 1];
    const { data, error, isLoading } = useSWR (
      ['news', newsId], fetchNewsDetailsById(newsId)
    );
    console.log(' news instance in the hook ', data);
    return {
      data,
      isLoading,
      isError: error
    }
  }


  // component
  import React, { useMemo } from 'react'
import { useParams } from 'react-router-dom';
import { formatDate } from '../../../helpers/dates';
import { useNewsDetailsBySlug } from './hooks';
const NewsDetails = () => {
  const { id: slug } = useParams();

  const reqObj = useNewsDetailsBySlug(slug);

  const { data: dataObj, isLoading, isError } = reqObj;

  console.log(reqObj)

  if (!isLoading && !dataObj && !isError) {
    return <h2>No State onlyyy !!</h2>;
  }
  if (isLoading) {
    return <h2>Loading...</h2>
  }
  if (isError) {
    return <h2>Oops !! something went wrong while fetching details of the news</h2>
  }

  return (
    <div>
        <h3>{dataObj.title}</h3>
    </div>
  )
}

export default NewsDetails;

State of my component remains like this

{data: undefined, isLoading: false, isError: undefined}

Logs I am seeing in my inspect window is this

args in fetch news  6
service.js:12 my promise  PromiseĀ 

hooks.js:10  news instance in the hook  undefined

component.jsx:12 {data: undefined, isLoading: false, isError: undefined}

service.js:9 api data -- Exact data in want to be in my component

Can someone tell like why the state object in my component is not updating? I also want that I get value of isLoading: true first.


Solution

  • Your issue is with:

    useSWR(..., fetchNewsDetailsById(newsId));
    

    Here you're calling the fetchNewsDetailsById(newsId) function, and then using the returned promise from that function as the seocnd fetcher argument. The second fetcher argument to useSWR should be a function reference, not a promise:

    useSWR(
      ['news', newsId], () => fetchNewsDetailsById(newsId)
    );