1

Alright so I have this code here

  componentDidMount() {
    var _this = this;
    var cbname = `fn${Date.now()}`;
    var script = document.createElement("script");
    script.src = `https://www.reddit.com/reddits.json?jsonp=${cbname}`;

    window[cbname] = function(jsonData) {
      _this.setState({
        navigationItems: jsonData.data.children
      });
      delete window[cbname];
      document.head.removeChild(script);
    };

    document.head.appendChild(script);
  }

I can't figure out at all how this accesses the reddit.json call to retrieve data, it looks very confusing for someone who just learned how ReactJS works. Also this is the state + component constructor, incase its needed:

export default class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      activeNavigationUrl: "",
      navigationItems: [],
      storyItems: [],
      title: "Please select a sub"
    };
  }

For the rest of the code refer to https://github.com/ssorallen/react-reddit-client , the code piece is located at src/app.js

Looking at the above code, I understand everything up to the line that instantiates script.src After that, I dont understand what's going on, even the window[cbname] part. I tried googling around pieces of it but it got too confusing, especially whats really being done with window[cbname], and why the code piece is appending a child(script) to the head of the document after deleting it.

adriam
  • 431
  • 3
  • 8
  • 16

1 Answers1

0

this is using the JSONP API - which essentially requires the API to wrap the JSON into a function callback

eg { "foo": "bar" } with callback=foo would call a global function called foo and pass the JSON as an object.

in this case, it registers window['fn' + Date.now()] as the callback. once the API calls it, it sets state and deletes the global function.

see What is JSONP all about?

TLDR: JSONP needs a global function on the window object. when called, it sets state and removes itself and the script tag. JSONP is useful to circumvent CORS

Dimitar Christoff
  • 26,147
  • 8
  • 50
  • 69