Skip to content
Advertisement

How to fetch .json data from URL?

I have problem with fetching data from URL. When I write data inside of a file, app works great, but when I try to call same data from URL, I get error.

I made a test with small app where everything was inside of a App.js file, and it worked. But new app is kinda devided in multiple files, and this is where problem starts.

Here is events.js where I call data and code works:

JavaScript

This is how I try to fetch data, which doesn’t work:

JavaScript

NOTE: .json file should be fine, becasue it works in small app.

Advertisement

Answer

I think you are trying to initialize the state with the content of a json file loaded from an URL: if I were you, I would create an action specifically to do that. You’ll need a library to handle asynchronous processes, like redux-thunk or redux-saga.
Here is a quick example with redux-thunk:

JavaScript

Now, with a reducer implemented for the action RECEIVE_FAVORITES, you can call the function fetchFavorites: it will send the request and fill the state however you do it in the reducer.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement