0

With code below, I am able to render the content of the local text file to the web page, but when I use a URL to get the text file to render it on the webpage, I get " " because the state is defined null. To render a local text file I had to use import text from './filepath.txt. How I can render text content from a URL link?

import React, { Component } from "react";
import "./App.css";
import text from "./myText.txt";

class App extends Component {

state = { loading: true,
          docText: null,
    };

componentDidMount() {

        fetch( text, { mode: "no-cors" }
            // { 
            //   method: "GET",
            //   headers: {
            //     "Content-Type": "application/text",
            //   },
            // }
           ).then((response) => { return response.text();})
            .then((data) => {
            this.setState({ docText: data, loading: false });
            console.log({ docText: data });
                })
            .catch((error) => { console.log(error);
             });
      }

render() { 
    return (
         <div className="App">
     <h1>Fetched Data</h1>
         <div>
             {this.state.loading || !this.state.docText ? (
             <div>Loading...</div>
                  ) : ( 
            <div> 
            <div>{this.state.docText}</div>
            </div>
            )}
            </div>
            </div>
            );
        }
}
export default App;
Zoe
  • 27,060
  • 21
  • 118
  • 148
xiang
  • 95
  • 2
  • 10

1 Answers1

2

Before rendering the content to the DOM, verify whether the file is read from the url.

Please try the below code,

fetch("https://URL/file").then((r)=>{r.text().then(d=>console.log(d))})

try steps mentioned in this question Get text from a txt file in the url

Dificilcoder
  • 449
  • 5
  • 11
  • unable to see anything in console. – xiang Aug 05 '21 at 11:35
  • Please check the url, whether the data is available there or it requires some permission (like login credentials or password) to read data from the url – Dificilcoder Aug 06 '21 at 12:04
  • Data is available in the text file and it doesn't require any permission to access it. You may check the link given in the sandbox code given above. – xiang Aug 06 '21 at 12:18