ReactJS – Trying to access the title of an object I'm pulling from a webpage online, but getting these errors

Advertisements

I’m trying to create a news website with ReactJS and I’m getting three various warnings/errors when I try to run the page. I can get it to display the article link properly when I don’t include the title. I still get the two first warnings in this case, but when I try to access the article’s title it won’t load the page at all.

Any help is greatly appreciated.

The warnings/errors:

Warning: Each child in a list should have a unique "key" prop.

Warning: Invalid value for prop href on tag.

Uncaught Error: Objects are not valid as a React child (found: object with keys {rendered}). If you meant to render a collection of children, use an array instead.

LatestArticles.js

import React, { useState, useEffect } from "react";
import Article from "./Article";

function LatestArticles() {
  const [posts, setPosts] = useState(React.useState("waiting..."));

  function ArticleGrabber() {
    useEffect(() => {
      fetch("URL")
        .then((response) => response.json())
        .then((data) => {
          setPosts(data);
          console.log(data);
        })
        .catch((error) =>
          console.log("Authorization failed: " + error.message)
        );
    }, []);
  }

  ArticleGrabber();

  return (
    <div>
      <h3>Latest Articles</h3>
      {posts.map((post, index) => (
        <ul>
          <Article key={index} post={post} />
        </ul>
      ))}
    </div>
  );
}

export default LatestArticles;

Article.js

import React from "react";
import "../Article.css";

function Article(post) {
  return (
    <div className="theArticle">
      <h3>{post.post.title.rendered}</h3>
      <a href={post.post.link}>Article content</a>
    </div>
  );
}

export default Article;

>Solution :

As far as I can see I see two Issues. 1. State inside an Inside, and the UseEffect Hook. Try this:

 const [waiting, setWaiting] = useState("waiting...")
 const [posts, setPosts] = useState([]));

    useEffect(() => {
     const articleGrabber = () => {
             fetch("URL")
        .then((response) => response.json())
        .then((data) => {
          setPosts(data);
          console.log(data);
        })
        .catch((error) =>
          console.log("Authorization failed: " + error.message)
        );
     }
    articleGrabber() 
    }, []);

Leave a ReplyCancel reply