0

How do you splice from both ends of an array either simultaneously or sequentially such that "leftsplice" number of fields are spliced from left and "rightsplice" number of fields are spliced from original array not the one after doing leftsplicing. Any tips?

  const [skillname,setSkillName] = useState(["Engineering", "Product", "Organization", "Business", "Market", "Customer"]);
    setSkillName(skillname => skillname.splice(0,leftsplice))
    let temp=-5+leftsplice;
    setSkillName(skillname => skillname.splice(temp, rightsplice))

This is doing only leftsplicing. PS: leftsplice, rightsplice are working as desired. I console.logged them

arvind
  • 49
  • 6
  • 3
    Don't mutate objects that are stored in the state. So don't splice the array at all. Use `slice` three times to get three new arrays instead. – Quentin Dec 08 '21 at 09:56
  • This is quite similar to: https://stackoverflow.com/questions/54069253/usestate-set-method-not-reflecting-change-immediately maybe even a duplicate. – Yoshi Dec 08 '21 at 09:58
  • and restrain from using hardcoded numbers, where does the -5 come from, what is it related to. – Branchverse Dec 08 '21 at 10:00

1 Answers1

1

Your code in splicing is okay, but you should only use setSkillName after both leftsplice and rightsplice is done by saving it on a temporary variable, I haven't tested this code below but it is answering the question "How to splice both at the same time from a state" :

function whatever() {
  let tempSkillName = [...skillname]
  tempSkillName = tempSkillName.splice(0,leftsplice))
  let temp=-5+leftsplice;
  tempSkillName = tempSkillName.splice(temp, rightsplice))
  setSkillName(tempSkillName)
}
JC ONG
  • 89
  • 7