0

I'm working on a React project and I want to load some raw (string) Markdown files to an array of objects.

What I want to do - but it doesn't work:

links_file.js

export const links = ["path to file 1.md", "path to file 2.md", ...]

logic.js

import { links } from "links_file.js"

componentDidMount() {
      links.map( (link, index) => {
         fetch(link).then(resp => {
              return response.text()
         }).then( text => {
              // Make a shallow copy of the files
              let files = [...this.state.files];
              // Make a shallow copy of the file to mutate
              let updatedFile = {...files[index], content: text};
              // Make a shallow copy of the item to mutate and replace the property
              files[index] = updatedFile;
              //Set the state to the new copy
              this.setState({files});
         })
      })
}

Console logging text gives me the index.html instead of the raw md content I want.

This works:

import file1 from 'path to file 1.md';
import file2 from 'path to file 2.md';

componentDidMount() {
     fetch(file1).then(resp => {
          return response.text()
     }).then( text => {
          this.setState(file1: text);
     })
}
6
  • 1
    "it doesn't work" Could you be more specific? What are the symptoms? How do you know that it doesn't work? Is this.state.files only filled with 1 of the 2 (or more) results? Commented Sep 4, 2021 at 10:47
  • @3limin4t0r I've updated the question explaining why it doesn't work. As for tye this.state.files, that an array of objects, the object has a property content which I want to set with the raw data from those files. Commented Sep 4, 2021 at 10:56
  • Does it fetch the right files? For instance, if you look into the network tab of the developer tools, does it request the files you expect? Commented Sep 4, 2021 at 11:00
  • @A_A The files are being fetched correctly. But the Fetch status is 304: Not modified. Well, flushing the cache returns a 200 when the files are fetched Commented Sep 4, 2021 at 11:06
  • And if you console.log(link, text), it gives you "path to file 1.md", "<!doctype><!-- index.html -->"? Commented Sep 4, 2021 at 12:48

1 Answer 1

1

if you are using create-react-app, make sure your files are in the public folder

they need to be exposed via a web URL first, for you to use the fetch API

you can't fetch files from your file system

working example: https://codesandbox.io/s/react-read-text-files-from-public-sk4es

1

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you @oieduardorabelo! Moving those files to the public folder solved the issue! :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.