Search code examples
javascriptarraysreactjsapireddit

Reddit API preview pictures not showing in ReactJs


I can't access the image source in preview.image inside of the Reddit API, though I have access to everything else and am able to preview my Cards with for example subreddit Names.

export default {
    search: function(searchTerm) {
      return fetch("http://www.reddit.com/search.json?q="+searchTerm+'&sort=new'+'&limit=30'+'&include_over_18=on')
        .then(res => res.json())
        .then(data => data.data.children.map(data => data.data))
        .catch(err => console.log("ERROR"));
    }
}

This is where I put the Api array into a state

const [myResults, setResults] = useState ([]);

const redditSearch = () =>{ 
        reddit.search(item).then(results => {
        setResults(results);
    });
  }

here I try to pass a default image, whenever the preview property isn't existing in a post

let image = myResults.preview ? myResults.preview.images[0].source.url : 'https://lh3.googleusercontent.com/8Vw-7MAm558750a4M55fiOlUf7lP2cYnFuqSWynrygIiyEEiQQDa_xxHKYOX83L0UD2T=s180';


<div className="Cards">{myResults.map((results, index) => (<ReactBootStrap.Card key={index} className="CardBody" style={{ width: '18rem' }}>
    <ReactBootStrap.Card.Img variant="top" src={image} />
    <ReactBootStrap.Card.Body >
    <ReactBootStrap.Card.Title>{results.subreddit}</ReactBootStrap.Card.Title>
      <ReactBootStrap.Card.Text>
        Filler Text
      </ReactBootStrap.Card.Text>
      <ReactBootStrap.Button variant="primary">Go somewhere</ReactBootStrap.Button>
    </ReactBootStrap.Card.Body>
    </ReactBootStrap.Card>))}</div>
    </React.Fragment>);

My Cards also working as intended

preview:
  enabled: true
  images: Array(1)
    0:
      id: "lRWiJ4V8rBsmyXu1pcwE5_aWHwuIT3JT2HTjo-DbhOA"
      resolutions: (6) [{…}, {…}, {…}, {…}, {…}, {…}]
      source:
         height: 2822
         url: "exampleUrl.jpg"
         width: 2117

this is how the data looks inside the API its an array

preview.images[0].source.url 

this is the path


Solution

  • Managed to fix It

    let image = myResults.preview ? myResults.preview.images[0].source.url : 'https://lh3.googleusercontent.com/8Vw-7MAm558750a4M55fiOlUf7lP2cYnFuqSWynrygIiyEEiQQDa_xxHKYOX83L0UD2T=s180';
    

    Couldn't have worked since it's being initialized before anything is being searched for. instead i pasted it raw into the the src

    <ReactBootStrap.Card.Img variant="top" src={results.preview ? results.preview.images[0].source.url : 'https://lh3.googleusercontent.com/8Vw-7MAm558750a4M55fiOlUf7lP2cYnFuqSWynrygIiyEEiQQDa_xxHKYOX83L0UD2T=s180'} />
    

    But that wasn't the end of it. Because of legacy reasons written in the official reddit dev documentation I had to add a '&raw_json=1' to my request

    return fetch("http://www.reddit.com/search.json?q="+searchTerm+'&raw_json=1'+'&sort=new'+'&limit=30'+'&include_over_18=on')