Transform the JSON format received from the API endpoint to make it suitable for use in the component

I'm working on a react-native app that fetches event data from a wordpress endpoint.

Below is the JSON I receive from the wordpress API. How can I restructure it to fit into my calendar component?

Where should I handle this restructuring in my app? Currently, I dispatch an action in my app.js:

  eventsFetchData(
    "http://wordpress.rguc.co.uk/index.php/wp-json/tribe/events/v1/events"
  )
);

export default class App extends Component {
  render() {
    return (
      <Provider store={store}>
        <AppNavigation />
      </Provider>
    );
  }
}

My event reducer updates the state on success:

export function events(state = [], action) {
    switch (action.type) {
        case 'EVENTS_FETCH_DATA_SUCCESS':
                return {
        ...action.events
      };

        default:
            return state;
    }
}

In my page component, I use mapStateToProps:

const mapStateToProps = state => {
    return {
        events: state.events,
    };
};

The desired format for the JSON data is as follows (start date and title):

{{
                        "2012-05-08(startdate)": {
                            dots: [
                                {
                                    key: "vacation(title)",
                                    color: "blue",
                                    selectedDotColor: "white"
                                },
                                {
                                    key: "massage",
                                    color: "red",
                                    selectedDotColor: "white"
                                }
                            ],
                            selected: true
                        },
                        "2012-05-09": {
                            dots: [
                                {
                                    key: "vacation",
                                    color: "blue",
                                    selectedColor: "red"
                                },
                                {
                                    key: "massage",
                                    color: "red",
                                    selectedColor: "blue"
                                }
                            ],
                            disabled: true
                        }
                    }}

This is the current data structure I have and I need to extract the title and startdate fields into the format mentioned above:

{
   "events":[
      {
         ...
      },
      {
         ...
      },
      {
         ...
      }
   ],
   "rest_url":"http:\/\/wordpress.rguc.co.uk\/wp-json\/tribe\/events\/v1\/events\/?page=1&per_page=10&start_date=2017-12-28 23:59:00&end_date=2019-12-29 14:52:47",
   "total":"3",
   "total_pages":1
}

Answer №1

In my view, it is advisable to handle the information directly from the API response and then save it in redux to suit your requirements. Modifying the original response should be avoided.

If you mention dispatch, I assume you are utilizing redux. If not, you might want to consider implementing it as it will prove beneficial in this particular situation. You can pass your events array through your action, iterate over it, and store the relevant data in an object map within the reducer.

case FETCH_DATA_SUCCEEDED: {
  const events = { ...state.events };
  action.events.map(event => {
    const { year, month, day } = event.start_date_details;
    const startDate = `${year}-${month}-${day}`;
    events[startDate] = {
      dots: [
        {
          key: event.title,
          // add your customized calendar styles
        }
      ],
      selected: true,
      disabled: false
    };
  });

  return {
    ...state,
    events
  };
}

I have structured the above code according to the format required by your calendar component. However, you could also think about storing each event based on its id, including startDate, endDate, title, etc., within each event object. Then, when you connect your calendar component, you can iterate over the events in redux and create a new object specifically tailored for that particular use case.

Answer №2

When receiving data from wordpress, it is essential to understand the key value that needs to be mapped as a dot object containing key, color, and selectedColor. Are you utilizing redux to manage the data fetched via the wordpress end-point?

To achieve this mapping, we can look at the code snippet below. The resultObj will hold the desired output format.

// Sample Code
// Let's assume the received data from wordpress is stored in an object named wordpressObj.
// We iterate over the events array of this object, extract the start date, and add all the dots for this start date into the array.
var resultObj = {};
wordpressObj.events.map((eachObj) => {

   startDate = eachObj.start_date_details.year+"-"+eachObj.start_date_details.month+"-"+eachObj.start_date_details.day;

   if(!resultObj.hasOwnProperty(startDate))
   {
      resultObj.startDate.dots = [];
   }
   tempObj = {};
   tempObj.key = eachObj.title;
   tempObj.color = "blue";
   tempObj.selectedDotColor = "white";

   resultObj.startDate.dots.push(tempObj);

   // Selected and deselected logic will be implemented here, setting both as true for now.
   resultObj.startDate.selected = true;
   resultObj.startDate.disabled = true;
});

console.log(resultObj);

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

By default, Nuxt 2.15.7 is automatically installed when you create a new Nuxt app

I am looking to develop a Nuxt app (version 3) using Vue. However, when I run the command npm create nuxt-app@version mousa, it automatically installs Nuxt2. How can I install Nuxt3 instead with this command? ...

Unable to retrieve cookies from the client side | Working with NodeJS and JavaScript

Code for Handling Cookies on the Server-Side: res.cookie('test', 'value', { expire: 400000 + Date.now(), httpOnly: false }); res.writeHead(302, { 'Location': 'localhost:4000/test', }); res.end(); Code for Acce ...

Exploring the versatility of Grails 3 profiles through JSON rendering and implementing a One to Many relationship with

I am currently utilizing gson and web profile in my project. The domain I am working with is: package json import grails.rest.* @Resource(readOnly = false, formats = ['json', 'xml']) class Hero { String name String data S ...

Ways to handle a JSON object within Highcharts

Recently, I encountered a challenge while working with an array JSON object in JavaScript. My goal was to process this data to display it as a series section using the example of a highchart called column-rotated-labels. The JSON object consisted of two co ...

Is it possible to link an HTML select element to a changing array in JavaScript?

Let's say I have an empty HTML select element. <select id="options"> </select> Can I link a JavaScript array to this select so that when the array is modified, the select options update accordingly? Alternatively, do I need to resort to ...

Incorporate this form created externally onto my website

I have been working on my website and I am looking to incorporate a form that opens up once the login button is clicked. This form was generated using an online form builder which provides an embed code for seamless integration onto websites. Below, you wi ...

Creating a Custom "Save As" Dialog in HTML5 and JavaScript for Downloading Files

I have developed a NodeJS/Express application that is capable of generating and downloading an Excel document (created using ExcelJS) when a user clicks on a button. Currently, the file gets automatically downloaded to the default download location of the ...

Explore in MegaMenu Pop-up

At my workplace, the internal web portal features a MegaMenu with a popup menu that includes a Search input field. The issue I am encountering is that when a user starts typing in the search bar and moves the mouse off of the megamenu, it disappears. It ...

Maintain text while transitioning to another page

On my webpage (refer to image for details), users need to select options through a series of steps. The process involves clicking on a link in the top box, then entering a search term in the searchbox to display relevant links in div1. Clicking on a link ...

JQuery not functioning properly within a dynamically loaded AJAX section

After loading some pages with Ajaxtabs, I encountered an issue where jQuery and Owl Carousel were not functioning properly. The classes and styles from Owl Carousel were not being applied to the divs after loading parts of the page. Here is an example of ...

What is the method to set precise values on a range slider?

Currently, I am developing a PHP website that requires a slider for displaying the years of publications. In essence, I need the slider to navigate through the different years when the publications were released. // Database connection and other PHP code ...

Tips for updating a JSON file in PowerShell by replacing a specific string with a variable

I have a JSON object shown below. I am looking to substitute the '$content' value with 'test/abc' in the JSON. { "$version": "0.0.1", "description": "", "content": { "url": "$content", "tag": { "version": "0.0.1", ...

Combining four numbers to calculate a total with the click of a button

I am currently attempting to calculate the sum of 4 entries in 4 separate text fields, and everything appears to be working correctly except that when I click the button, the sum is not being set. For example, if I enter the number 1 in each text input, th ...

Spring Boot does not validate JSON data types

Here is an example of a JSON data structure: "name": { "title": "Mr", "firstName": "somename", "middleName": "middleName", "lastName": "Micheal", "maid ...

How to assign a preset value to a text area in AngularJS

While working with PHP and AngularJS, I have a requirement to specify the default value for a textarea. I prefer not to utilize ng-init="textarea = ''" as the data to populate is extensive. Similarly, I want to avoid using AJAX to prevent additi ...

What is the best way to link this to a function in AngularIO's Observable::subscribe method?

Many examples use the Observable.subscribe() function in AngularIO. However, I have only seen anonymous functions being used like this: bar().subscribe(data => this.data = data, ...); When I try to use a function from the same class like this: update ...

Ways to troubleshoot JsonCPP issue related to the getMemberNames() method?

In the example provided, the JSON file has the following structure: { "strings": [ { "key_one": "value_one!" }, { "key_two": "value_two!" } ] } On the other hand, the C++ file contains the following code snippet: Json ...

typescript warns that an object may be potentially null

interface IRoleAddProps { roles: Array<IRole> } interface IRoleAddState { current: IRole | null } class RoleAdd extends React.Component<IRoleAddProps, IRoleAddState> { state = { current: null, } renderNoneSelect = () ...

Using Jquery and Ajax to pass an extra PHP variable to a server-side script

I am working with a dropdown select box where the selected option is sent to a server-side script using Ajax. <select id="main_select"> <option selected="selected" value="50">50</option> <option ...

jQuery is not updating the div as expected

While typing out this question, I'm hoping to uncover a solution that has eluded me so far. However, just in case... About a year ago, I successfully implemented something similar on another website and went through the code meticulously. Surprisingl ...