1

I am working on a project where I have 4 options, but I should only be able to select one option per screen. The option pushes an object with an id and a score (based on the screen) to an array in the state. So if I make one selection and change to another, I'd like to able to remove the previous object and append the new one in an array in the state (for each screen). I have script to append and remove the object if I'm clicking on the same option, but I'm not sure what I would do to replace the object with a new one if I make a selection then immediately go to another.

The array looks as follows:

scores: [
  [{id: "G1", score: "4"}, {id: "B1", score: "3"}, {id: "O1", score: "2"}, {id: "R1", score: "1"}],
  [{id: "B2", score: "4"}, {id: "G2", score: "3"}, {id: "R2", score: "1"}, {id: "O2", score: "4"}]
]

Here is the code I have now:

handleScore = (id, score, idx) => {
  const {
    statements,
    scores
  } = this.state;
  if (statements[0][idx].isSelected) {
    this.setState({
      scores: scores.map((item, index) => index === 0 ? [...item, {
        'id': id,
        'score': score
      }] : item)
    });
  } else {
    this.setState({
      scores: scores.map((item, index) => index === 0 ? item.filter(i => i.id !== item[0].id) : item)
    });
  }
}

and in the render method I have:

<div
  className={`statement ${(this.state.statements[0][index].isSelected) ? 'selected' : ''}`} key={item.id} onClick={e => {
      e.preventDefault();
      this.handleScore(item.id, match.params.score, index)
    }}>
  <a href="#">{item.statement}</a>
</div>

Thank you in advance!

1 Answer 1

1

I don't know what you are trying to do, but you can use the splice() method to remove an item from an array. Check this repro on Stackblitz to see the result, and here is the code in case it does not works:

import React, { Component } from "react";
import { render } from "react-dom";
import Hello from "./Hello";
import "./style.css";

const App = () => {
  const [data, setData] = React.useState([
    {id: 0, score:10},
    {id: 1, score:20},
    {id: 2, score:30},
    {id: 3, score:40},
  ]);

const displayItems = () => {
  return data.map((item, index) => {
    return (
    <div>
      <span>id: {item.id}, score: {item.score}</span>{' '}
      <button onClick={() => replaceItem(item, index)}>Replace item</button>
    </div>
  )});
}

const replaceItem = (item, index) => {
  const newItem = {id:4, score: 50};

  let newData = [...data]; 

  // -----Replace ONE ('1') item at specific index by the newItem
  // newData.splice(index, 1, newItem); 
  // -----OR remove an item and place another at the first index
  newData.splice(index, 1); // remove item from array
  newData.unshift(item); // Put the item at the first index of the array
  //------
  setData(newData); // set your newData array as the new state
}
  return (
    <div>
      {displayItems()}
    </div>
  );
};

render(<App />, document.getElementById("root"));

I placed two use case of splice so you can coment/uncomment to see the result.

Sign up to request clarification or add additional context in comments.

1 Comment

I figured it out and your response helped a lot. I was making this way more difficult than it needed to be. All I needed to do is check if there is something in the array, and if there is, splice it out. Ugh. Thank you so much!!!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.