Search code examples
javascriptarraysreactjsframerjs

How to remove an item from array if it's been clicked (and if it already has been previously added to an array)?


How do you remove an item from array if it's been clicked (and if it already has been previously added to an array)?

I have a Framer X (React) prototype which pulls down football betting information down from an API, like so:

const API = "https://api.myjson.com/bins/i461t"

// [1]
export const data = Data({
    matches: [],
    chosenBets: [],
})

// [2]
const fetchData = async (endpoint, callback) => {
    const response = await fetch(endpoint)
    const json = await response.json()
    data.matches = json
}

Each match has odds associated with it: for the home and away team, as well as a draw:

enter image description here

When the user selects an odd, it becomes highlighted and is added to a chosenBets array:

export function PopulateMatches(): Override {
    return {
        matches: data.matches,
        onClick(obj, index) {
            data.chosenBets.splice(index, 1, obj)
            console.log(data.chosenBets, "data.chosenBets")
        },
    }
}

enter image description here

When I click the same odd again, it is deselected (the red background removed from the button but not the data object chosenBets)

enter image description here

How do I remove the item from the chosenBets data object?

Code can be viewed here: https://github.com/A7DC/FramerXTEST1

Edit: full code

import * as React from "react"
import { Data, Override, Stack, Frame } from "framer"
import { MatchCard } from "./canvas"

//// Pulling down mathches

const API = "https://api.myjson.com/bins/i461t"

// [1]
export const data = Data({
    matches: [],
    chosenBets: [],
})

// [2]
const fetchData = async (endpoint, callback) => {
    const response = await fetch(endpoint)
    const json = await response.json()
    data.matches = json
}

// App.tsx
export function PopulateMatches(): Override {
    return {
        matches: data.matches,
        onClick(obj, index) {
            data.chosenBets.splice(index, 1, obj)
            console.log(data.chosenBets, "data.chosenBets")
        },
    }
}

// [4]
fetchData(API, {})

Solution

  • Array.splice() can also be used to remove an element from an array.

    data.chosenBets.splice(index, 1); // Deletes the element at specified index.
    

    Also, adding to chosenBets array looks wrong. Second argument should be 0 when adding.

    data.chosenBets.splice(index, 0, obj); // Adds the element at specified index.
    

    Then onClick() function would look like

    onClick(obj, index) {
      if (data.chosenBets[index]) {
        // Remove object.
        data.chosenBets.splice(index, 1);
      } else {
        // Add object.
        data.chosenBets.splice(index, 0, obj); 
      }
    }