Browse Source

Start to replicate the page-fetching in React

Getty Ritter 4 years ago
parent
commit
a54a444c8c
1 changed files with 50 additions and 1 deletions
  1. 50 1
      js/index.jsx

+ 50 - 1
js/index.jsx

@@ -1,4 +1,53 @@
 import React from 'react';
 import ReactDOM from 'react-dom';
 
-ReactDOM.render(<div>Hello World</div>, document.getElementById('root'))
+class Page extends React.Component {
+    constructor(props) {
+        super(props);
+        this.state = {
+            loaded: false,
+            modified: null,
+            rendered: null,
+            slug: null,
+            source: null,
+            title: null,
+        };
+    }
+
+    componentDidMount() {
+        if (!window.location.hash) {
+            window.location.hash = "#index";
+        }
+        const loc = window.location.hash.substring(1);
+        fetch(`/p/${loc}`, {headers: {'Accept': 'application/json'}})
+            .then(res => res.json())
+            .then(
+                (res) => {
+                    console.log(res);
+                    this.setState({
+                        loaded: true,
+                        modified: res.modified,
+                        rendered: res.rendered,
+                        slug: res.slug,
+                        source: res.source,
+                        title: res.title,
+                    });
+                },
+                (error) => {
+                    this.setState({
+                        page: "failed",
+                    });
+                }
+            );
+    }
+
+    render() {
+        if (this.state.loaded) {
+            return <div dangerouslySetInnerHTML={{__html: this.state.rendered}} />
+        } else {
+            return <div>Loading...</div>
+        }
+    }
+}
+
+ReactDOM.render(<Page/>, document.getElementById('root'))