What is the best method to retrieve .json information from a website address?

Having trouble retrieving data from a URL. When the data is stored in a file, the app functions correctly. However, when attempting to fetch the same data from a URL, an error occurs.

I tested this with a small app where everything was contained within a single App.js file and it worked fine. But with the new app split into multiple files, the issue arises.

Below is the events.js file where the code successfully calls for data:

import {
 TOGGLE_FAVORITE_EVENT
} from '../const';
import toggle from './toggle';

let data = [
    {
        type: 'PARTY',
        title: 'Party in the Club',
        address: '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 am attempting to fetch data, which is not working:

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: The .json file should be compatible since it works in the small app.

Answer №1

One possible solution for initializing the state with JSON data from a URL is by creating a specific action for it. You would need to utilize a library that can handle asynchronous operations, such as redux-thunk or redux-saga.
Below is a simple example using redux-thunk:

// store
import thunk from 'redux-thunk'
import { createStore, applyMiddleware } from 'redux'
import reducer from 'state/reducers'

export const configureStore = () => {
  /* thunk acts as a middleware in Redux, allowing you to call action creators that return functions instead of objects. These functions can dispatch multiple times (see fetchFavorites) */
  const middlewares = [thunk]
  let store = createStore(reducer, applyMiddleware(...middlewares))
  return store
}  

// actions
// standard action that returns an object
export const receiveFavorites = function(response){
  return {
    type: "RECEIVE_FAVORITES",
    response
  }
}

// this action returns a function that takes dispatch as a parameter 
export const fetchFavorites = function(){
  return function(dispatch){
    console.log('sending request')
    return fetch('http://some-url.com/test.json')
      .then(response => response.json())
      .then(response => {
        dispatch(receiveFavorites(response))
      })
      .catch(error => {
        console.log(error)
      })
  }
}  

Once you have a reducer set up for the RECEIVE_FAVORITES action, you can invoke the fetchFavorites function to make the request and update the state accordingly within the reducer.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Unable to properly access required file path through HTML source

I have a confidential folder named 'inc' where I store sensitive files such as passwords in php connection files. This folder is located at the same level as the 'public_html' folder. I successfully accessed php files with database conn ...

What is the best way to transmit a JavaScript array to a servlet via AJAX?

Within a textarea, users input one or more email addresses separated by commas. Here is my JavaScript code: var emails = $("#emails").val().split(","); if (emails.length == 0) { window.alert("Please enter an email address."); ...

Delete Refresh Support Jquery

I am attempting to have the div recentactivity only refresh when the Remove button is clicked < a href='#' onclick=\"javascript:remove_wall('$id')\">Remove However, every time I click on the link, it keeps trying to re ...

Navigating through JSON in Python

I made an error while storing json strings in a database. Instead of saving the string as JSON, I mistakenly stored it as the string representation of the object. What I received was: my_jstring['field'] and I saved it as a string in the dat ...

The route in my Node.js Express application appears to be malfunctioning

I am facing an issue with my app.js and route file configuration. Here is my app.js file: const express = require('express'); const app = express(); const port = process.env.PORT || 8080; const userRoute = require('./routes/user.route' ...

Prevent selection on all elements except for input fields with the type of text

I am facing a challenge where I need to prevent selection on a website page for everything except input[type=text] elements. The answer provided in this accepted response to a similar query almost solves the issue. However, it doesn't stop users from ...

When incorporating reduce into your code, remember to expect an undefined

Imagine you have an array like this: const novels = [ { id: 1, name: 'The Da Vinci Code', genre: 'Mystery', author: { name: 'Dan Brown', birthYear: 1964, }, releaseYear: 2003, }, { ...

Tips for correctly displaying a Youtube video's length in Java (android) retrieved from the Youtube API

One of the calls we use in Android is: https://www.googleapis.com/youtube/v3/videos?id=7nwwdhZzVro&part=contentDetails,statistics&key=YOUR_KEY When this call is made, it returns the following information: { "kind": "youtube#videoListResponse", " ...

Configuring Google Maps API (including charts) for maximum height of 100%

I am having trouble getting my map to display at 100% height using the Google Maps API. I've encountered similar issues in the past with the Google Charts API as well. From what I've gathered, it seems like setting the height of the html and bod ...

Adding a Logo/Client Slider to Your Bootstrap Website

I'm currently working on a website and trying to incorporate a logo/client slider (linked here). <script src="https://code.jquery.com/jquery-2.2.0.min.js" type="text/javascript"></script> <script src="https://cdnjs.cloudflare.com/ajax/ ...

Divide a column containing dictionaries into individual columns using pandas

I have data stored in a postgreSQL database. Using Python2.7, I am retrieving this data and converting it into a Pandas DataFrame. However, the last column of this dataframe contains dictionaries of values. The DataFrame df is structured as follows: Statio ...

Unpacking a JSON object with multiple nested arrays and efficiently transferring the data to SQL using Bulk Copy

Looking for advice on how to deserialize JSON data with multiple subarrays and display it on a web page? Here's what I have: NEXT STEP : Next, I plan to insert this data into an SQL database using bulk copy features. Sample C# Code var myData = new ...

Effective implementation of the useReducer hook across various React components to manage form state

My current project is proving to be quite challenging as I navigate through the step-by-step instructions provided. Initially, I was tasked with creating a BookingForm.js component that houses a form for my app. The requirement was to utilize the "useEffec ...

Retrieve information from the pouchdb database

After successfully storing data in PouchDB, I'm wondering how to retrieve this information and display it in HTML using AngularJS. var db = new PouchDB('infoDB'); function getData(){ $.getJSON('test.json', function(data) { ...

Tips for showcasing varied information on Morris Chart

I am working with a Morris chart that is populated with a collection of data, each item containing 6 different data values. My goal is to switch between displaying two different sets of data. For example, I want to show the 'Target' data always ...

Can multiple if statements be executed simultaneously in plain Javascript? If yes, what is the method to do so?

Currently, I'm developing a game using canvas in HTML, CSS, and vanilla JavaScript. I've successfully created two characters with movement controls assigned to player 1 and player 2. However, a challenge arises when waiting for one player to move ...

angular2 angular-entity directive

I have developed a component that accepts a template: export class TemplateParamComponent implements OnInit { @Input() items: Array<any>; @Input() template: TemplateRef<any>; } Here is the HTML code: <template #defaultTemplate le ...

having trouble retrieving data from JSON array using JavaScript

I am having trouble fetching the JSON value to determine if the person in the photo is wearing glasses. The value is spread across four arrays: photos, tags, attributes, and glasses. My goal is to check if the value "value" is either true or false. I have ...

Where is the best place for my function to reside: /mixins or /plugins directory?

Suppose I am utilizing an external package like vue-js-modal and have imported it in the file /plugins/vue-js-modal.js: import Vue from 'vue' import VModal from 'vue-js-modal' Vue.use(VModal) Imagine I have a function that utilizes vu ...

Enhance the appearance of a bokeh plot with real-time updates using

My question is similar to the one found at this link. I have a website that includes various elements, such as a table and a bokeh plot. I want to update these elements based on user input. While I have figured out how to update the table, I am struggling ...