I want to create React base application (the game "worlde") so I can put it on my Git (to make my portfolio). I want to use the fetch
API, so I created a JSON file with 500 words, but I don't know how to use it. The more I look for solutions, the more confused I get.
Do you know a way (website to upload it or even through localhost
) to fetch my data?
Thank you!!
CodePudding user response:
response
is my json file name, and results
is the name of the object in my json file which contains all the data. (You need to wrap your json data inside an object so when you try to reach the data it will know what you want to get)
So if I go to the browser and search: http://localhost:8000/results
I see all the data in my json file, which is in the results
object.
Now the second step is to use fetch
to get it, by simply calling the path above. Like this in my case:
fetch("http://localhost:8000/results")
.then((response) => {
if (!response.ok) {
throw Error("Failed to fetch. ERROR: " response.statusText);
} else {
return response.json();
}
})
.then((data) => {
console.log("This is the JSON data: " data )
})
.catch((err) => {
//...Do some staff when error occurs.
});
Important Notice: Pay attention that the other terminal which is running your json file on the server is not closed. Because if you want to fetch the data, you always need to make sure that command is still running , and then fetch it from the server with fetch
.
Hope it helps!