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:
import { TOGGLE_FAVORITE_EVENT } from '../const'; import toggle from './toggle'; let data = [ { type: 'PARTY', title: 'Party in the Club', adress: 'New York', date: '9. 9. 2019.', image: '', text: [ 'Party description...' ], coordinates: [50, 50], id: 'events_1' } ]; let events = (state = data, action) => { switch(action.type){ case TOGGLE_FAVORITE_EVENT: return toggle(state, action.payload.id); default: return state; } } export default events;
This is how I try to fetch data, which doesn’t work:
import { TOGGLE_FAVORITE_EVENT } from '../const'; import toggle from './toggle'; // WP REST API const REQUEST_URL = 'http://some-url.com/test.json'; let data = fetch(REQUEST_URL) .then(response => response.json() ) .then(data => console.log(data) ) .catch(error => console.log(error)); let events = (state = data, action) => { switch(action.type){ case TOGGLE_FAVORITE_EVENT: return toggle(state, action.payload.id); default: return state; } } export default events;
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:
// store import thunk from 'redux-thunk' import { createStore, applyMiddleware } from 'redux' import reducer from 'state/reducers' export const configureStore = () => { /* thunk is a redux middleware: it lets you call action creators that return a function instead of an object. These functions can call dispatch several times (see fetchFavorites) */ const middlewares = [thunk] let store = createStore(reducer, applyMiddleware(...middlewares)) return store } // actions // standard action returning an object export const receiveFavorites = function(response){ return { type: "RECEIVE_FAVORITES", response } } // this action returns a function which receives dispatch in parameter export const fetchFavorites = function(){ return function(dispatch){ console.log('send request') return fetch('http://some-url.com/test.json') .then(response => response.json()) .then(response => { dispatch(receiveFavorites(response)) }) .catch(error => { console.log(error) }) } }
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.