rss2json API: feed is not updated in real time

166 Views Asked by At

I created a blog component to my portfolio to display my medium posts, I wanted to test if it would render new articles so I published a new article to test it but it doesn't change even on refresh, the length of the array stay the same when i console.log(posts). I added timestamp as a paramter to the url in the second code but it didn't help either

useEffect(() => {
    const username = "@khaledb.yahya";
    const url = `https://api.rss2json.com/v1/api.json?rss_url=https://medium.com/feed/${username}`;
    axios
      .get(url)
      .then((response) => {
        const posts = response.data.items;
        setPosts(posts);
        console.log(posts);
      })
      .catch((error) => {
        console.error(error);
      });
  }, [username]);
useEffect(() => {
    const username = "@khaledb.yahya";
    const timestamp = Date.now();
    const url = `https://api.rss2json.com/v1/api.json?rss_url=https://medium.com/feed/${username}&t=${timestamp}`;
    axios
      .get(url)
      .then((response) => {
        const posts = response.data.items;
        setPosts(posts);
        console.log(posts);
      })
      .catch((error) => {
        console.error(error);
      });
  }, [username]);
2

There are 2 best solutions below

0
devpolo On

Looks like you should have a look to the pricing of rss2json.

Since you are under free plan (no API key in your url), your feed will be updated every hours.

4
Yassin Mo On

The problem with this code is that the username variable is defined inside the useEffect hook and is used as a dependency for the hook. This can cause an infinite loop, because the username variable is changing on every render, which triggers the useEffect hook to run again and again

To fix this problem, you should move the username variable outside of the useEffect hook and include it in the component's state or props

import React, { useState, useEffect } from "react"; import axios from "axios";

const MyComponent = ({ username }) => {
  const [posts, setPosts] = useState([]);

  useEffect(() => {
    const url = `https://api.rss2json.com/v1/api.json?rss_url=https://medium.com/feed/${username}`;
    axios
      .get(url)
      .then((response) => {
        const posts = response.data.items;
        setPosts(posts);
        console.log(posts);
      })
      .catch((error) => {
        console.error(error);
      });
  }, [username]);

  return (
    <div>
      {/* Render the posts here */}
    </div>
  );
};

export default MyComponent;