What is the best way to incorporate a new item into Redux with a nested data structure similar to this? Specifically, I am looking to add new

Seeking assistance with dynamically pushing new items to a deeply nested choice array in order to render react native TextInput components using the map function. Below, you will find details on the data structure, reducer design, and other relevant code snippets.

Use case scenario:
UI: 
 Question:     _________
 Choice:       _________    Add more choices
 Right Choice: _________    Dropdown menu populated from choice array

 Next                  Add New Question

Upon clicking 'add new question', a new object is added from dynamicMCQGenerationDataFormat[0], each containing two questions with properties such as question, choice, and right choice. This setup necessitates adding new items to the choice array and eventually updating their content as well.

The data structure dynamicMCQGenerationDataFormat looks like this:

[
  {
    "question": "What",
    "choice": ["choice"],
    "rightChoice": ""
  }
]

Reducer snippet:

import {
  EXAM_UPDATE,
  REFRESH_EXAM,
  INSERT_NEW_QUESTION,
  INSERT_NEW_CHOICE,
  UPDATE_QUESTION
} from '../actions/types';
import dynamicMCQGenerationDataFormat from '../assets/MCQGenerationFormat/dynamicMCQGeneration.json';

const INITIAL_STATE = {
  description: "",
  level: "",
  status: "",
  mcq: dynamicMCQGenerationDataFormat
};

export default (state = INITIAL_STATE, action) => {
  switch (action.type) {
    // Reducer logic here
  }
};

Action Creator excerpt:

import { Actions } from 'react-native-router-flux';
import {
  EXAM_UPDATE,
  EXAMS_FETCH_SUCCESS,
  INSERT_NEW_QUESTION,
  UPDATE_QUESTION,
  INSERT_NEW_CHOICE
} from './types';
// Action creator functions defined here

Snippet showing how the action creator is called in a React Native component:

pushNewQuestion() {
    this.props.insertNewQuestion(dynamicMCQGenerationDataFormat[0]);
}

This showcases the structure of dynamicMCQGenerationDataFormat used for inserting new questions.

Answer №1

Great news! I have successfully resolved the issue at hand. If you encounter a similar problem when updating deeply nested data and struggle with denormalizing it, please take a look at this solution.

case ADD_NEW_CHOICE:
  return {
    ...state, mcq: state.mcq.map((mcq, i) => i === action.payload.idx ? {...mcq, choice: [ ...mcq.choice, action.payload.value]} : mcq)
  }

case UPDATE_CHOICE_VALUE:
  return {
    ...state, mcq: state.mcq.map((mcq, i) => i === action.payload.idx ? {...mcq, choice: [ ...mcq.choice.map((choice, i) => i === action.payload.sIdx ? action.payload.value : choice ) ] } : mcq)
  }

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

Is there a jQuery selector that can mimic :starts-with or :ends-with to search for specific text?

Exploring the jQuery website's selectors list, one can find selectors for starts-with and ends-with on attributes. Additionally, there is a unique :contains selector designed for text search: alert( $("div").find("span:contains(text)").html() ); Is ...

Here's a method to extract dates from today to the next 15 days and exclude weekends -Saturday and Sunday

Is there a way to generate an array of dates starting from today and spanning the next 15 days, excluding Saturdays and Sundays? For example, if today is 4/5/22, the desired array would look like ['4/5/22', '5/5/22', '6/5/22' ...

Is there a way for me to choose a single file while executing the migrate-mongo up command?

Hey there! I'm looking to execute the command migrate-mongo up in just one specific file. Currently, when I run the command migrate-mongo up, it processes all pending migration files. Is there a way to target only one file for execution? For example: ...

Efficiently populating a multidimensional array in PHP for rapid data insertion

My current project involves using PHP to populate a multidimensional array with data. I have implemented two different methods for achieving this task, both of which should work equally well. If I were to repeat this process 1000 times consecutively, whic ...

How is it possible for TypeScript to enable the importing of dependencies that it ultimately cannot utilize during runtime?

Take a look at my sample project by following this link: https://github.com/DanKaplanSES/typescript-stub-examples/tree/JavaScript-import-invalid I have developed a file named main.ts: import uuid from "uuid"; console.log(uuid.v4()); While type ...

Alter the component and then refresh it

I am encountering an issue with a component that has an event handler for a "like" icon. The goal is to allow users to click the like icon, update the database to indicate their liking of the item, and then re-render the component to visually reflect this ...

Determine the elapsed time in seconds between two specified moments

I am trying to implement two input fields in my HTML, one for a starting point and another for an end point. The user will enter two times like this: For example: [8:15] - [14:30] alert("XXXXX seconds") I want to calculate the number of seconds between 8 ...

Mastering JQuery: Techniques for Managing Events Across Numerous Elements

My view page utilizes Ajax and JQuery to retrieve data from Codeigniter's controller, then presents it in HTML format. Below is the code for the Ajax post: $(document).ready(function(){ var fileId = 0; var wrapper = $("#preference"); ...

How can I implement a loop using .then in JavaScript?

Looking to understand the .then concept in JavaScript, I am curious if it is feasible to generate a series of .then's using a for loop. request.send(myRequest) .then(r => console.log(r, 0)) .then(r => console.log(r, 1)) .then(r => ...

How can I update the title of the NavigationBarRouteMapper without altering the current route in React Native?

Here is a snippet of code that outlines the NavigationBarRouteMapper: var NavigationBarRouteMapper = { ... , RightButton(route, navigator, index, navState){ return( <TouchableHighlight onPress={()=>{ //When this ...

Is it possible for slices to refer to arrays or slices with varying index ranges, or is there a clever workaround available?

Something along these lines newSlice := make([]byte, 5) newSlice[0:2] = originalArray[3:5] // Instead of copying originalArray[3:5], I want newSlice[0:2] to point to it newSlice[2:5] = originalArray[0:3] // Likewise, I want newSlice[2:5] to reference or ...

What sets {props.children} apart from conventional objects?

Currently, I am deep diving into React by taking a crash course. The topic at hand is nested components and props, which has left me slightly confused. In my attempt to create a simple comment section, similar to thishttps://i.sstatic.net/7uNlj.png ...

Using reduce in JavaScript to form a fresh object

I've been struggling with creating an object using reduce from a nested array. The task is to generate a new object with keys named _uid and values matching the initialValue from the objects that contain both properties. I have written a function that ...

Unable to transfer AJAX data to PHP script

Trying to figure out how to send AJAX data to PHP. While I am comfortable with PHP, JavaScript is a bit new to me. Incorporating HTML / JavaScript <input type="text" id="commodity_code"><button id="button"> = </button> <script id="s ...

Looping through multiple table rows with AngularJS ng-repeat

I am currently working on making the code below functional, which involves data being retrieved from an API: ... <tbody ng-repeat="verbinding in data.connection" style="border-bottom:2px solid black;"> <tr> <td></td> ...

Although the buttons have the class ui-btn-inline, they do not exhibit inline behavior in the

My header has 2 rows. The first row is a ui-grid-solo and the second row is a ui-grid-c. The issue I'm facing is with the alignment of buttons within the first row. Despite using the class ui-btn-inline, the buttons are not behaving as inline elements ...

Trouble arises when attempting to parse multiple objects from a JSON file using JavaScript

Encountering JSON parsing issues with multiple JSON objects. JSON data is essential for JavaScript functionality. { "name": "Sara", "age": 23, "gender": "Female", "department": & ...

The issue arises when the cache code in jQuery Ajax interferes with the callback function, causing it to

I encountered an issue with my code related to cache. The problem arises when there is an ajax call with a callback in the success function. var localCache = { /** * timeout for cache in millis * @type {number} */ timeout: 30000, ...

Tips for implementing orderBy and filter in ng-repeat when working with an object instead of an array

I am facing a data structure that looks like this: $scope.people = { "ID123": { name_de: "Andre", name_en: "Anrew", age: 30, description: "He is the father of xyz and . . .", . . . ...

I'm puzzled as to why my createDoorMethod is returning a string value instead of a number, even though I am passing it a number. Can someone help me

Currently enrolled in a web development course, I am diving into the world of Angular 2 and TypeScript. Despite following along with the video tutorial and using the same code, my implementation is not working as expected, leaving me puzzled. Here is the ...