Search
 
SCRIPT & CODE EXAMPLE
 

JAVASCRIPT

How to spread state into a specific array

const DataReducer = (state, action) => {

 const { type, payload } = action; 

 switch (type) {

    case 'ADD_DATA': {

      const copy = [...state];

      copy[0] = {
        ...copy[0], 
        data: [
          ...copy[0].data, {
            id: Math.floor(Math.random() * 999),
            name: 'Bob'
          }
        ]
      };

      return copy;

    }
  }
}

const state = [{title: 'Names', data: []}, {title: 'Meal', data: []}];

const newState = DataReducer(state, { type: 'ADD_DATA', payload: { name: 'Bob' } });

console.log(newState);
 Run code snippet
Comment

How to spread state into a specific array

const DataReducer = (state, action) => {

 const { type, payload } = action; 

 switch (type) {

    case 'ADD_DATA': {

      const copy = [...state];

      copy[0] = {
        ...copy[0], 
        data: [
          ...copy[0].data, {
            id: Math.floor(Math.random() * 999),
            name: 'Bob'
          }
        ]
      };

      return copy;

    }
  }
}

const state = [{title: 'Names', data: []}, {title: 'Meal', data: []}];

const newState = DataReducer(state, { type: 'ADD_DATA', payload: { name: 'Bob' } });

console.log(newState);
 Run code snippet
Comment

PREVIOUS NEXT
Code Example
Javascript :: React Native Swift Escaping closure 
Javascript :: Syntax for npx 
Javascript :: Error thrown after ending the audio track / array of tracks in React Native Track Player 
Javascript :: How to make this code cleaner? react native 
Javascript :: socket io check send 
Javascript :: async mutex 
Javascript :: python regex consecutive characters 
Javascript :: splunk : json spath extract 
Javascript :: in node.js with express how to remove the query string 
Javascript :: Pass 3 of the same thing to ExpressJS with a form 
Javascript :: yaml request body json 
Javascript :: get oinput value clojurescript 
Javascript :: show code in console very good 
Javascript :: coercion in javascript mdn 
Javascript :: Uncaught (in promise) TypeError: dispatch is not a function 
Javascript :: socket io inside route express not working 
Javascript :: how to install ghost js 
Javascript :: open close menu javascript 
Javascript :: JavaScript: Cycle through three-state checkbox states 
Javascript :: React Native - iOS Release build crashing 
Javascript :: Accessing Function Declared Outside Constructor But Inside Class 
Javascript :: Using an object of functions as a parameter into a function 
Javascript :: send a message in the first channel discord.js 
Javascript :: NavBar with divs 
Javascript :: Backbone Notes Miscellaneous 
Javascript :: discord.js sync channel permissions 
Javascript :: document.getelementbyid add number 
Javascript :: nested object in javascript 
Javascript :: cookies javascript 
Javascript :: javascript oop 
ADD CONTENT
Topic
Content
Source link
Name
4+4 =