React/Redux Reddit Client Project, getting error when fetching data from api

Hello everyone,

I’m currently working on the reddit client project. Here is a link to the project: Reddit client project

I’m currently trying to fetch the comments from a particular post in a subreddit. Here is my code:

import React, {useState,useEffect} from 'react';
import logo from './logo.svg';
import {FaReddit} from "react-icons/fa";
import { SubredditContainer } from './features/subredditSection/subredditContainer';
import {MainfeedContainer} from './features/mainfeedSection/mainfeedContainer';

import './App.css';

function App() {

  /*
  useEffect(() => {
    fetch('https://www.reddit.com/r/pokemon.json')
    .then(fetchedData =>{
      if(fetchedData.status !==200){
        console.log('error');
        return;
      }
      fetchedData.json().then(data=>{
        console.log(data.data.children);
      });
    })
  });*/

  const [articles, setArticles] = useState([]);
  const [firstComment,setFirstComment] = useState('');

    useEffect(() => {

        const fetchRedditArticles = async() => {

         const redditArticles = await fetch ('https://www.reddit.com/r/pokemon.json');
         const json = await redditArticles.json();
         setArticles(json.data.children);

         
         const articleComments = json.data.children[5].data.permalink;
         console.log(articleComments);

         const redditComments = await fetch('https://wwww.reddit.com' + articleComments + '.json');
         const json_2= await redditComments.json();
         console.log(json_2);

        }
        fetchRedditArticles();
    },[]);
    
    console.log(articles);
  
  return (
  <>
    <header className ="App-header">
      <div className="logo_background">
      <FaReddit size="2rem"/>
      </div>
      <div className="title">Reddit Minimal</div>
    </header>
    <body className="body_section">
      <main className="main_section">
        <h1>This is the main section</h1>
        {
          (articles!==null) ? articles.map((article,index) => <MainfeedContainer key={index} article={article.data} />):''
        }
      </main>
      <aside>
      <SubredditContainer/>
      </aside>
    </body>

  </>
    
  );
}

export default App;

However, I am getting this error when I try to fetch the data:

I also get this when I click the reddit url in the error:
Screen Shot 2021-09-06 at 11.45.48 AM

It seems that I need some kind of authentication code. However, the project instructions say that an authentication code is not necessary to access the comments.

Any idea on how to get the comments from a post without using an authorization code? Or perhaps is my fetch endpoint wrong? Any help is appreciated. Thanks for your help everyone! Happy coding :slight_smile:

Hey there,
if you use the JSON api of Reddit, you can access everything without authentication.
The problem you encounter here is a security issue.
You’re still working with localhost, right? Then check out step 12 of the ravenous lesson. That’s how I solved it.

1 Like

Hi @mirja_t,

How’s it going? Thanks for your help again! I followed the steps from step 12 in the ravenous lesson. However, I am still getting an error.

I was granted temporary access from cors anywhere:

Then I prepended the fetch request with https://cors-anywhere.herokuapp.com/. Here is my code:

 useEffect(() => {

        const fetchRedditArticles = async() => {

         const redditArticles = await fetch ('https://www.reddit.com/r/pokemon.json');
         const json = await redditArticles.json();
         setArticles(json.data.children);

         
         const articleComments = json.data.children[5].data.permalink;
         console.log(articleComments);

         const redditComments = await fetch('https://cors-anywhere.herokuapp.com/https://wwww.reddit.com' + articleComments + '.json');
         const json_2= await redditComments.json();
         console.log(json_2);

        }
        fetchRedditArticles();
    },[]);

This is the error I receive:

When I go to the url given in the error I get this message:

Do I need to include some header so I can bypass the security error? Thanks again :slight_smile:

Hmm, from what I remember I just clicked the on the link ‘Request temporary access to the demo server’ and that solved the issue for me for the time of development. I’m not sure anymore if I did that only while doing the ravenous project or both actually.
But the query params for reddit data without OAuth are limited. I requested data for comments like this:

getPostComments = (id, subreddit) => {
    const url = 'https://www.reddit.com/';
    return fetch(`${url}${subreddit}/comments/${id}.json`) ...

Hi @mirja_t ,

Thanks for your guided help once again. I tried what you suggested but still can’t get past the CORS security policy. Here is what I get:

Here is my code:

  useEffect(() => {

        const fetchRedditArticles = async() => {

         const redditArticles = await fetch ('https://www.reddit.com/r/pokemon.json');
         const json = await redditArticles.json();
         setArticles(json.data.children);

         
         const articleComments = json.data.children[5].data.permalink;
         console.log(articleComments);

         setId(json.data.children[5].data.id);
         console.log(id);

         setSubreddit(json.data.children[0].data.subreddit);
         console.log(subreddit);

         const redditComments = await fetch('https://wwww.reddit.com/' + subreddit + '/comments/'+ id + '.json');
         const json_2 = await redditComments.json();
         console.log(json_2);

        }
        fetchRedditArticles();
    },[id,subreddit]);

I have a question: should the ${subreddit} be in the form as r/[subreddit] or just [subreddit]? I tried both ways, but didn’t work.

Maybe the id value is wrong. Here is a screenshot of where I got the id number, pjnwpk:

All the best! Cheers :slight_smile:

This CORS error is something that is fixed in the HTTP headers in your server settings. The default settings prevent access from another domain. So that is something you wouldn’t fix in your App but in your XAMP or MAMP settings as I understand it. For my localhost (I’m a Mac user and use MAMP) a simple click on the provided link did the trick. Maybe you find an alternative solution here:

What I passed as subreddit is a string that looks like this:

'r/dataisbeautiful'

The id I pass is the post’s Id.

The query for the comments looks like this for example:

https://www.reddit.com/r/DesignPorn/comments/pjedb8.json
1 Like

Hi @mirja_t ,

Thanks for your help! It turns out that my url formatting was incorrect and that was why I was getting problems. For some reason I don’t even need to use the cors-anywhere url prepended to my url. The cors error disappeared after I fix my fetch url. I always appreciate your help! Take care :slight_smile:

1 Like

You’re welcome :slight_smile:
I don’t remember if I had to tackle the CORS problem when working on the Reddit project. It might just have been necessary for the Ravenous project.
Good luck with your Reddit development!

1 Like

Hello @mirja_t,

Just out of curiosity. What document did you refer to for the comments query for the reddit api? Did you use this document: https://github.com/reddit-archive/reddit/wiki/JSON

I tried looking in that document on how to fetch comments, but couldn’t find it.

All the best!

Hey,

neither could I. I fetched the main data, printed everything to the console and referred to that.