How can I use a pull in the contents of a json file in one JS file for use in another JS file?

The JSON file is in the same folder as my project. I am getting the json file contents using fetch but I need the contents in another JS file. Do I use localStorage and pull that in somehow into the other file? Or do I fetch the json in my main file and somehow use async/await in EVERY function in that second file?

I need the contents of the json file to populate my HTML file via the 2nd JS file. IS this even possible? I can’t use export/import from my computer. I need to find a solution for this so any ideas would be greatly appreciated.

I mean if I have to I upload all the files to my public_html folder on my site and test it that way, but that sounds like a bad idea. Local storage would work for what I am trying to do.

I’m a little unclear on what you’re doing, but typically you would have one area of code that is responsible for getting data and it either sets a local state or passes the relevant data to other pieces of code.

I’m using a user-supplied list of words to output onto the page as buttons. It’s a writing program for people with motor control issues that find it easier using a mouse than a keyboard.

As of now, I have the list of words in my javascript file. I don’t know how to pass the file contents to local state. I am passing the data to the next function but the page is already built. It’s almost like I have to generate the page AFTER the file is uploaded.

I think we would need to see your code because we don’t really know how to help if we don’t know what you are currently doing.

Here is the CodePen link.

This is the only project I have right now for my portfolio page. It seems like I have to put it up with hard-coded data as an example.

If I am understanding you correctly, you currently have the words you want displayed when you hover over a letter stored in a space separated string in the variable wordsToSplit and you want to know if you could store those words in a separate file and then load them into the app? I don’t see why not?

If the file is publicly available from a web server you can use fetch to get the file and then read in the information stored in that file.

There are also ways you can read in a file from your local computer as well, but this requires that the user select the file each time they open your app (i.e. it can’t be done automatically, it must be user initiated for security reasons).

You could do a combination of both, load in a default words list using fetch and then allow them to load in a customized words list from their own computer if they want.

I’m not sure if this answers your question completely or if I missed the mark?

I tried fetch with a local file - I got it to output on the page and in the console but it did not populate the alphabetical menu. I would like users to upload a sample of their writing, proper nouns they like to use, and emails addresses.

FYI, I am building this for my aunt who has cerebral palsy and finds it very difficult to use a keyboard, but she has an assistive mouse. I was thinking that besides loading the file from their computer, I could save the content in localStorage which would be good until they cleared their cache, cookies, etc. I also would like them to somehow download the HTML, CSS, and js files and then bookmark the HTML page. Then it would be easier for them to communicate, especially if they also have difficulty speaking.

Maybe I did fetch wrong. I am going to try it again except on the Proper Nouns section which only has a couple of code blocks for that section. Otherwise, I’d have to get it hosted somewhere, maybe a non-profit that helps people with physical disabilities. A friend forwarded my CodePen link to someone they know at Magee Rehab Hospital.

I have code for the FileReader link you added. As a matter of fact, I was also able to store my list of words in localStorage. I guess I didn’t do the async/await thing correctly. I need the code to wait to populate all the words until the file uploads finishes and then to get the words from localStorage.

This doesn’t quite make sense. You can’t use fetch directly with local files on your computer, it has to go through a web server, the argument you are passing into fetch is a URL. Perhaps you are running a web server on your computer and fetching through localhost? Or did you mean that you uploaded a file to some place on the internet and fetched it from there?

If you want to read a file directly on your computer without needing to go through a web server then you need to use the FileReader API.

Correct, you can’t populate something until you have the information to populate it with :slight_smile: After you get the information (whichever method you use) then you would most likely store it in some sort of data structure and then call a function that can populate the words using that data structure. The key here is that you call this function after you get the information. The method you are using to get the information will determine where you do that. Fetch uses promises, FileReader uses events, localStorage uses standard synchronous functions.

My guess would be that you would want your aunt to be able to load this information from a local file on her computer so you would use FileReader to get the words initially. Then you can store them in localStorage so she doesn’t have to load the file every time she opens the app.

What you are referring to here is called a Progressive Web App (PWA). To get you started check out this article on FCC.

One thing I might recommend is that you move this out of codepen and do the development on your local computer. The size of this is getting way too big for codepen. You should probably start thinking about splitting up your JS code into separate, more manageable files. All modern browsers support modules now. Your UI is getting fairly complicated so you might even consider switching to a framework.

Also, if I can recommend some accessibility enhancements, I would not use mouseover to trigger the words list, I would use click instead. It’s way too easy to accidentally move your mouse out of the words container and then they all disappear and you have to go back and hover over the letter again to get your words back. Or maybe someone is using some sort of pointer device with their mouth and can’t “hover” over the letters? At the least maybe have an option to let the user choose between displaying the words on hover or on click.

Is your aunt going to be able to help you test this? If so, I would start testing as early as possible. This is a great idea and a very admirable goal but there are going to be a lot of accessibility issues. If you really only care about your aunt being able to use this then you can just focus on her issues. But if you want other people to be able to use it then you really need to start focusing on accessibility for everyone from the very beginning. For example, I know your primary focus is using a mouse, but people who use a keyboard (or assistive tech that simulates the keyboard) could benefit from this so you would want to make sure it is completely keyboard accessible as well.

Good luck with this. I hope it can help your aunt.

  1. The url for the fetch is the file path. I was able to get it but it wouldn’t perform the split function lower down in the code. I was able to get it into local storage:
let userinputarea = document.querySelector('.userinputarea')
const input = document.querySelector('.fileupload');

function getMyText() {
  input.addEventListener('change', async () => {
    let file = input.files[0];

    const fileContent = await file.text();
    console.log(fileContent);

    // dont actually need the 4 lines directly below
    const lines = fileContent.split(/[^a-zA-Z'-]+/gi);
    let x = JSON.stringify(lines);
    document.getElementById("useroutput").innerText = x;
    let y = JSON.parse(x);

    localStorage.setItem("word", fileContent);
    localStorage.getItem("word");
  })
}
getMyText();

const x = getMyText();

let y = JSON.stringify(x);
let z = JSON.parse(y);
document.getElementById("useroutput").innerText = z;

// I changed userWords to proper to try it with the proper nouns section
let userWords = z;

I also tried the following but this is where I got the error with the split line in the Fx splitWords() - I didn’t know where to put the async await in that Fx:

async function loadJSON(url) {
  const res = await fetch(url);
  return await res.json();
}

let userWords = loadJSON('./test.json').then(data => {
  console.log(data);
  return data;
});

I wanted to try and store the words in localStorage that one js file created, then get the content in localStorage with my main.js file.

  1. My aunt won’t be able to load anything. I’m also thinking of other people using it. I’ll look into the FileReader API and the Progressive Web App article.

  2. I’m working on my local machine, the CodePen is where I have the code so people can see it. This is for my portfolio - I’m a beginner. Modules, Frameworks? I’m not there for those things. It stinks that my next project idea is an inventory tracker for small businesses and it will need the inventory numbers to do all the analysis. I want to get back to studying JS and taking a React course I bought. Looks like my portfolio Live link for this one will have to have the words in the JS file.

  3. I can change the hover to click. I’m giving it to my aunt this Saturday so I’m hoping she can give me real feedback as a user. Yes, I would like other people to use it. For anyone who can’t use a mouse but can use a keyboard, the text area is there. But if they can do that why wouldn’t they just do that in an email body or word doc? I set the tabindex to -1 or it would take a long time to get to what you want.

Thanks!

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.