Skip to content

Instantly share code, notes, and snippets.

@tvler
Last active December 10, 2017 08:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tvler/1a80bb8dc5d0f07ef64e8ce6037421a7 to your computer and use it in GitHub Desktop.
Save tvler/1a80bb8dc5d0f07ef64e8ce6037421a7 to your computer and use it in GitHub Desktop.
A setState function to immutably splice an array property
// Thanks to https://vincent.billey.me/pure-javascript-immutable-array
import React, { Component } from 'react';
const setStateArraySplice = (
stateKey,
arrayStart,
arrayDeleteCount,
...items
) => ({
[stateKey]: array,
}) => ({
[stateKey]: [
...array.slice(0, arrayStart),
...items,
...array.slice(arrayStart + arrayDeleteCount),
],
});
class extends Component {
state = { prop: [true, true, false] };
componentDidMount() {
this.setState(setStateArraySplice('prop', 2, 1, true));
// state = { prop: [true, true, true] };
}
render = () => false;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment