Last active
December 10, 2017 08:57
-
-
Save tvler/1a80bb8dc5d0f07ef64e8ce6037421a7 to your computer and use it in GitHub Desktop.
A setState function to immutably splice an array property
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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