1

My function keeps pushing duplicates and i don't know why.

Is it possible to update my code so that state contains only dates that are clicked once and removed when clicked twice?

So kind of being able to toggle dates in state.

(Because if misclicked, the user should be able te remove the selected date)

const [dates, setDates] = useState([])

const handleDayClick = (day) => {
    let newArray = [...dates];
    let indexItem = newArray.indexOf(day);
    indexItem === -1 ? newArray.push(day) : newArray.splice(day, 1);
    setDates(newArray)
  };

  useEffect(() => {
    console.log(dates);
  }, [dates]);

  return (
     <DayPicker selectedDays={dates} onDayClick={handleDayClick} />
  )

The day parameter in handleDayClick returns values as strings like:

Fri Mar 05 2021 12:00:00 GMT+0100 (Central European Standard Time)

I know there are related questions on Stackoverflow about this but i've been trying all of them the past hour and i can't find a fix.

If someone could look into it, that would be very helpful. Thanks in advance

5
  • 2
    You should remove an item using it's index newArray.splice(indexItem, 1); Commented Mar 8, 2021 at 10:19
  • @Yousaf .indexOf() doesn't use a callback, just the value. The .findIndex() method does. Commented Mar 8, 2021 at 10:20
  • 1
    @OriDrori oh right. My bad! Commented Mar 8, 2021 at 10:20
  • @OriDrori it is still pushing duplicates ... only after an item is added for the second time, then it gets deleted Commented Mar 8, 2021 at 10:39
  • Something to do with react state? Commented Mar 8, 2021 at 10:40

1 Answer 1

1

I worked on something similar with multiple arrays for my filter state and this was the solution I came up with.

    const clickHandler = (array, value, setter) => {
        if (array.includes(value)) {
            const newArray = array.filter(e => e !== value)
            setter(newArray)
        } else {
            const newArray = [...array, value]
            setter(newArray)
        }
    }

Where array is the state, value is the new date you might want to add or remove & the setter is the setState function of that state.

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

2 Comments

Hey Nobert, I would like to use your solution but can you help me explain how I would send the array, value and setter parameters with the clickhandler function?
The array is simply the initial state of your component (in your case, dates), the value is the new date you want to add (day), and the setter is the setState function (setDates), I made mine like this so it could work with 2 or more state arrays.

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.