Using defineModel macro does not trigger update of state in Vue.js

Please find at the below link a minimal example of the type of thing I am trying to achieve in Vue.

Vue SFC Playground link

In my real application, I have several pieces of data maintained in my store which require the same format of input. Therefore, I want to create a general input form which will receive the values from the parent component, and will create a 2-way binding between them, updating the store in the main component. This setup means I cannot simply update the store in the child component, since I don’t know at the input component’s level which of the store’s values the input component is managing.

However, when I set things up as in the example provided, the store is never updated when the values in the input changes. I cannot figure out why this is.

Apexcharts change color on bar per categories

I copied the demo for the apexcharts javascript Column Charts > Column with Group Label and I want to change the colors grouped by categories. How to do this? Here’s from the sample demo

var options = {
      series: [{
      name: "sales",
      data: [{
        x: '2019/01/01',
        y: 400
      }, {
        x: '2019/04/01',
        y: 430
      }, {
        x: '2019/07/01',
        y: 448
      }, {
        x: '2019/10/01',
        y: 470
      }, {
        x: '2020/01/01',
        y: 540
      }, {
        x: '2020/04/01',
        y: 580
      }, {
        x: '2020/07/01',
        y: 690
      }, {
        x: '2020/10/01',
        y: 690
      }]
    }],
      chart: {
      type: 'bar',
      height: 380
    },
    xaxis: {
      type: 'category',
      labels: {
        formatter: function(val) {
          return "Q" + dayjs(val).quarter()
        }
      },
      group: {
        style: {
          fontSize: '10px',
          fontWeight: 700
        },
        groups: [
          { title: '2019', cols: 4 },
          { title: '2020', cols: 4 }
        ]
      }
    },
    title: {
        text: 'Grouped Labels on the X-axis',
    },
    tooltip: {
      x: {
        formatter: function(val) {
          return "Q" + dayjs(val).quarter() + " " + dayjs(val).format("YYYY")
        }  
      }
    },
    };

    var chart = new ApexCharts(document.querySelector("#chart"), options);
    chart.render();

I tried below but the first color applied to all bar columns.

colors: ['#FF0000', '#00FFFF']

Other try is but still the same. I cant get to work to update bar columns per category:

fill: {
        colors: [function({ value, seriesIndex, w }) {
            
            index = Math.floor(seriesIndex / $group_count);

            return '#7E36AF';
            
        }]
    },

The url string is too long

I work with Excel and take a formula from a cell, then pair it into a tree object, then serialize it in json and pass it to the url so that my site on react takes this object in json and turns it back into a tree. But if the formula is too big, my url becomes more than 2000 and an error occurs.

Working with Excel API via C#

var json = JsonSerializer.Serialize(res);
var url = "http://localhost:3000/CreateTreePage/?jsonString=" + json + "&lettersFormula" + lettersFormula;

Here is the code for React

  useEffect(() => {
    // Получение параметра jsonString из URL
    console.log(props);
    const { jsonString } = queryString.parse(window.location.search);
    console.log(jsonString)

    if (jsonString) {
      const formulasObjectsArray = JSON.parse(jsonString.replace(/@/g, "#"));
      SetArray(formulasObjectsArray);
      console.log(formulasObjectsArray);
    }
  }, []);

Can I somehow transfer this data in another way, or can I compress it without loss?

How to AES decrypt data in Javascript with Python? [closed]

i want to decrypt this to get link
window.vInfo = {“ct”:”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”,”iv”:”364471abb4b931cb5c4fde437ce8ec0f”,”s”:”780b89edd53bf777″}

who can i decrypt it with python

TypeError: groupBy(…).map is not a function

I tried to group json data with specific key like that:

function groupBy(items) {
    return items.reduce((acc, curr) => {
      if (curr.league?.id) {
        const { id } = curr.league;
        const currentItems = acc[id];
    
        return { 
          ...acc,
          [id]: currentItems ? [...currentItems, curr] : [curr]
        };
      }
      return acc;
    }, {});
  }

    console.log(groupBy(matches))

Then I get a correct result like that

but when I tried to get data using The map() method like that :

groupBy(matches).map((match, index) => ( ..... ))

I get this error :

groupBy(...).map is not a function TypeError: groupBy(...).map is not a function

Any Idea?

I have to refresh the page everytime I change and upload a new profile picture how do I make so I don’t have to refresh the page

Below is the my profile page code I thinking I should use a callback along with another useEffect function but I’m not sure please help. You ignore all the code involving deleting, saving, and handling ingredients I just working on the profile card for right now plus those already work. I really just don’t want the user to have to refresh the page every time they upload a new image to see it. Unless you all have other fun way of getting around this or suggest i just make another modal telling the user to refresh the page or any other creative way to make this feature seem less bad and unprofessional. I’m a beginner and would really appreciate some help with this!

import React, { useEffect, useState, useCallback } from "react";
import Axios from "axios";
import Cookies from "js-cookie";
import Footer from "./Footer";
import Header from "./Header";
import "./Profile.css";

const Profile = () => {
  const [userData, setUserData] = useState({});
  const [savedIngredients, setSavedIngredients] = useState([]);
  const [ingredientName, setIngredientName] = useState("");
  const [ingredientQuantity, setIngredientQuantity] = useState("");
  const [selectedFile, setSelectedFile] = useState(null);
  const [showUploadModal, setShowUploadModal] = useState(false);
  const [previewImage, setPreviewImage] = useState(null);
  const [profilePictureURL, setProfilePictureURL] = useState(userData.profilePicture);

  const API = "http://localhost:3000"

  const handleFileChange = (event) => {
    const file = event.target.files[0];
    setSelectedFile(file);

    const previewImageURL = file ? URL.createObjectURL(file) : null;
    setPreviewImage(previewImageURL);
  };

  // Fetch email and username
  useEffect(() => {
    const authToken = Cookies.get("userToken");
    Axios.get(
      API+"/users/profile",
      {
        withCredentials: true,
        headers: {
          Authorization: `Bearer ${authToken}`,
        },
      }
    )
      .then((response) => {
        console.log("Profile response:", response.data);
        setUserData({
          username: response.data.username,
          email: response.data.email,
          profilePicture: response.data.profilePicture,
        });
        setProfilePictureURL(response.data.profilePicture)
      })
      .catch((error) => {
        console.error(error);
      });
  }, []);

  // Fetch and display saved ingredients
  const fetchSavedIngredients = useCallback(async () => {
    try {
      const response = await Axios.get(
        API+"/users/saved_ingredients",
        {
          withCredentials: true,
          headers: {
            Authorization: `Bearer ${Cookies.get("userToken")}`,
          },
        }
      );
      console.log("Response Data:", response.data);
      setSavedIngredients(response.data.savedIngredients);
      setIngredientName("");
      setIngredientQuantity("");
    } catch (error) {
      console.error(error);
    }
  }, []);

  const { username = "", email = "" } = userData || {};

  // insert ingredients into the fridge table
  const handleSaveIngredients = async () => {
    try {
      console.log("Input Ingredient Name:", ingredientName);

      const trimmedIngredientName = ingredientName.toLowerCase().trim();
      console.log("trimmedIngredientName:" + trimmedIngredientName);

      if (!trimmedIngredientName) {
        console.error("Ingredient name cannot be empty.");
        return;
      }

      if (!ingredientQuantity) {
        console.error("Quantity cannot be empty.");
        return;
      }

      const response = await Axios.post(
        API+"/users/profile_ingredient_list",
        {
          name: trimmedIngredientName,
          quantity: ingredientQuantity,
        },
        {
          withCredentials: true,
          headers: {
            Authorization: `Bearer ${Cookies.get("userToken")}`,
          },
        }
      );
      console.log(response.data);
      // Only fetch ingredients after a successful save
      fetchSavedIngredients();
      setIngredientName("");
      setIngredientQuantity("");
    } catch (error) {
      console.error(error);
    }
  };

  useEffect(() => {
    fetchSavedIngredients();
  }, []);

  const handleDeleteIngredient = async (ingredientName) => {
    try {
      const response = await Axios.delete(
        "http://localhost:3001/users/delete_ingredient",
        {
          withCredentials: true,
          headers: {
            Authorization: `Bearer ${Cookies.get("userToken")}`,
          },
          data: {
            name: ingredientName,
          },
        }
      );
      setSavedIngredients(response.data.savedIngredients);
    } catch (error) {
      console.error(error);
    }
  };

  const handleProfilePictureUpload = async () => {
    try {
      if (selectedFile) {
        const formData = new FormData();
        formData.append("profilePicture", selectedFile);

        const response = await Axios.post(
          API + "/users/upload_profile_picture",
          formData,
          {
            withCredentials: true,
            headers: {
              Authorization: `Bearer ${Cookies.get("userToken")}`,
              "Content-Type": "multipart/form-data",
            },
          }
        );

        // Update the user data with the new profile picture file name
        setUserData((prevUserData) => ({
          ...prevUserData,
          profilePicture: response.data.filePath.split('/').pop(),
        }));

        // Update the profile picture URL to trigger a re-render
        setProfilePictureURL(response.data.filePath.split('/').pop());

        setShowUploadModal(false);
      }
    } catch (error) {
      console.error(error);
    }
  };

  // console.log("Profile Picture File Name:", userData.profilePicture);

  return (
    <div>
      <Header />
      <div className="Profile-Card">
        <div className="Profile-Picture">
          <div className="picture-icon" onClick={() => setShowUploadModal(true)}> 
            <img 
              className="pic-icon" 
              src="./images/photo_icon.png" 
              alt="Add Photo"
            />
          </div>
          {userData.profilePicture ? ( 
            <img 
            className="profile-pic"
            src={`http://localhost:3000/uploads/${userData.profilePicture}`} 
            alt="Profile"
          />
          ) : (
            <img 
              className="default" 
              src="./images/profile_pic.jpg"
              alt="Default Profile"
            />
          )}
        </div>
        
        <div className="card-content">
          <h1>Profile</h1>
          <p>Username: {username}</p>
          <p>Email: {email}</p>
        </div>
      </div>
      {showUploadModal && (
        <div className="upload-modal">
          <div className="upload-modal-content">
            <input
              type="file"
              accept="image/jpg, image/png, image/jpeg"
              id="file"
              onChange={handleFileChange}
              style={{ display: 'none' }}
            />
            <label htmlFor="file" className="file-input-button">
              Change Profile Picture
            </label>
            {previewImage && (
              <img
                className="preview-image"
                src={previewImage}
                alt="Preview"
              />
            )}
            <button type="button" className="pic-upload" onClick={() => handleProfilePictureUpload()}>
              Upload Picture
            </button>
            <button type="button" className="pic-cancel" onClick={() => setShowUploadModal(false)}>
              Cancel
            </button>
          </div>
        </div>
      )}
      {/* <form>
        <h3>Ingredients:</h3>
        <input
          type="text"
          value={ingredientName}
          onChange={(e) => setIngredientName(e.target.value)}
          placeholder="Ingredient Name"
        />
        <input
          type="text"
          value={ingredientQuantity}
          onChange={(e) => setIngredientQuantity(e.target.value)}
          placeholder="Quantity"
        />
        <button type="button" onClick={handleSaveIngredients}>
          Save
        </button>
      </form> */}
      {/* <div>
        <h3>Saved Ingredients:</h3>
        <ul>
          {savedIngredients &&
            savedIngredients.map((ingredient, index) => (
              <li key={index}>
                {ingredient.name} - {ingredient.quantity}
                <button onClick={() => handleDeleteIngredient(ingredient.name)}>
                  Delete
                </button>
              </li>
            ))}
        </ul>
      </div> */}
      <Footer />
    </div>
  );
};

export default Profile;

A second fetch request from Google books API -> Open library API to take ISBN and return borrow availability

I’m making a search bar that brings up a book list from Google books based on a search term. It brings up title, author, isbn, etc. That part of the app currently all works.

Each list entry has a button, and on clicking it, I want information to come up showing whether the book is available for digital borrowing from Open Library. So I need a second API from open library, to take the isbn that google books returns, and use that to identify if the book is available on OL for digital borrowing.

I’m using isbn because that seems the most specific.

The first GoogleBooks call returns multiple data which is split into properties, e.g.

                  var bookTitle = book.volumeInfo.title;
                  var bookAuthor = book.volumeInfo.authors;
                  var bookDescription = book.volumeInfo.description
                  var bookThumbnail = book.volumeInfo.imageLinks.smallThumbnail;
                  var isbn =  book.volumeInfo.industryIdentifiers[0].identifier;

The last one is the isbn. So I’m wondering how to make the fetch call only use the isbn property, and not entire ‘response.json’ which includes everything. I need some help with figuring out the general structure of the second fetch call.

Also this is not one fetch inside another; because users don’t have to click the button after the book list renders, the second fetch is optional, but can only happen once the first one has run.

For reference, openlibrary api can filter by book availability, e.g.

https://openlibrary.org/search.json?q=harry%20potter&fields=*,availability&limit=1

Favicon is not showing up in google search results

I have added a favicon to my website interviewmogul.com. The favicon is correctly getting displayed on google chrome tab (next to title). However, it does not appear on google search results.

Earlier, I added incorrect icon size. Now, I have made a fix and added 48×48 size icon according to google documentation. I have re-requested indexing from google and my page has been indexed with latest changes. But, it does fix the issue.

Let me know if anyone can suggest any solution for this issue.

Thanks!

I can’t make a function call another one – Sending a Discord message on Google Sheet, with Apps Script

I’m trying to create a Google Sheet that works with Discord.
On Google Sheet, you can add some script with “Apps Script”.

The project is the following:
It’s a social media post planner, where people can write their ideas.

In a column, C, there’s the text that is a draft.
When the draft is ready to be reviewed by the manager, the writer can check the box in column D, and it will send a Discord Message (through a Discord Webhook) in a channel, taguing the manager that a new post is available to review.

The script works with 2 functions:

  1. onEdit(e); that will check everytime if a cell is edited
  2. postToDiscord(); that sends the message

If:

  1. the cell in column C is empty and the box is ticked (by mistake for exemple), a pop-up will appear and say “empty draft”exemple of onEdit working fine if cell is empty
  2. the cell isn’t empty, it should call a funtion: postToDiscord(), and execute the function test to see if there is some text

When I execute manually the postToDiscord function it does this:
enter image description here

The issue is, individually, each functions works, but when I mix them together, it doesn’t do anything.

function onEdit(e) {
  var range = e.range,
      col = range.getColumn(),
      row = range.getRow(),
      edited_value = e.value,
      ss = e.range.getSheet();
 
  //check if the box isn't ticked by accident to avoid spam
  if (col == 4 && edited_value == "TRUE" && ss.getRange("C"+row).getValue() == "") {
    Browser.msgBox("Empty draft!");
  }
  //execute the postToDiscord function if the draft cell is not empty
  else if (col == 4 && edited_value == "TRUE" && ss.getRange("C"+row).getValue() !== "") {     
    Browser.msgBox("The text is:" +ss.getRange("C"+row).getValue());
    postToDiscord();
  }
  else{
  }
}

//the function that manage discord messages
function postToDiscord() {
  const url = "https://discord.com/api/webhooks/[url]";
      
  const message = {
    content: "hi there"
    }

  const options = {
    'method': 'post',
    'payload': message
    }
    
  const res = UrlFetchApp.fetch(url, options);
}

Any superheroes among you?

I’m willing to have the postToDiscord works when the conditions are good in onEdit(e).

I tried things on other posts and it didn’t worked.

I might misunderstood them, because I actually never coded before, I just wanna learn some stuff for fun and create to for my company

And sorry in advance for mistakes!

Have a good one!

What is goin on with this If statement?

Why is this simple if statement not being triggered?

    console.log( data );

    ///////////////////////////////////////////////////////////////////////
    // last HR was furthest player ever hit - write to file
    ///////////////////////////////////////////////////////////////////////
    if ( data == "true" ) {

in the console log it returns the word true in string format. Why on Earth wouldn’t it trigger the if statement? When I change it to

    if ( data ) {

the code beneath executes. It triggers. I don’t understand. It has to be something far away in my code causing this problem..

Here is more of the code:

    $.ajax({

        method: 'POST', // specifying POST
        type: "post",
        async: true,
        data: {

            mode: 'checkLHRT',
            playerName: playerName,
            longestHR: pDistance,
            normalMode: true,
            pDistance: pDistance,
            exitVelo: ev,
            launchAngle: la,
            hangTime: ht

        },
        url: "dataBase.php",
        success: function( data ) {
            
            console.log( data );

            ///////////////////////////////////////////////////////////////////////
            // last HR was furthest player ever hit - write to file
            ///////////////////////////////////////////////////////////////////////
            if ( data == "true" ) {
                
                console.log( "writing trajectory to file" );
                console.log( ev, la, ht );

                let json = JSON.stringify( homeRunTraj );

                $.ajax({
                    
                    method: "POST", // specifying POST
                    type: "POST",
                    async: true,
                    data: {

                        mode: "updateLHRT",
                        homeRunTraj: json,
                        pDistance: pDistance.toFixed(2),
                        exitVelo: ev,
                        launchAngle: la,
                        hangTime: ht

                    },
                    url: "dataBase.php",
                    success: function( data3 ) {        
                        // drawHRTOG();
                    }

                });

            }

            if ( $('#loadingOG').is(':visible') ) {
                $("#loadingOG").fadeOut(250);
            }

        },
        error: function( data2 ) {

            if ( !$('#loadingOG').is(':visible') ) {

                $("#loadingOGMessage").html(
                'PROBLEMS CONNECTING TO SERVER'
                +'<div style="font-size: 14px;">THIS MAY BE YOUR INTERNET CONNECTION OR A SERVER ISSUE.</div>'
                +'<div style="font-size: 14px;">CONNECTION WILL BE RESTORED AUTOMATICALLY WHEN PROBLEM IS GONE.</div>'
                );
                $("#loadingOG").fadeIn(250);

            }   

        }

    });

    

MSW handler correctly intercepting request, but still resulting Axios network error

I’m kinda stumped – I’ve read through the many postings on here about Axios + MSW [1] [2] [3] and I can’t quite figure out where i’m going wrong.

What I’m doing – I’m trying to use MSW to intercept network requests that are made by Axios to inject responses for testing.

Code:

Test file (this will fail, I’m just trying to get it to work properly)-

/* eslint-disable @typescript-eslint/no-unsafe-argument */
import { jobsDashboardResponse } from "../../../tests/mocks/msw/handlers"
import { server as mswServer } from "../../../tests/mocks/msw/server"
import { bacalhauAPI } from "../bacalhau"

// Enable request interception.
beforeAll(() => mswServer.listen())

// Reset handlers so that each test could alter them
// without affecting other, unrelated tests.
afterEach(() => mswServer.resetHandlers())

// Don't forget to clean up afterwards.
afterAll(() => mswServer.close())

describe("Basic fetch of mocked API", () => {
    it("should GET /orchestrator/jobs", async () => {
        const jobsResponse = { a: 2 }

        mswServer.use(jobsDashboardResponse)
        mswServer.listHandlers()

        const jobs = await bacalhauAPI.listJobs()

        expect(jobs).toEqual(jobsResponse)
    })
})

BacalhauAPI server ts:

import axios, { AxiosInstance } from "axios"
import {
  JobListRequest,
} from "../helpers/jobInterfaces"

class BacalhauAPI {
  apiClient: AxiosInstance

  constructor(baseURL: string) {
    this.apiClient = axios.create({
      baseURL,
      headers: {
        "Content-Type": "application/json",
      },
    })
  }

  async listJobs(labels?: string[], nextToken?: string): Promise<JobsResponse> {
    try {
      const params: JobListRequest = {
        order_by: "created_at",
        reverse: true,
        limit: 10,
        labels: labels ? `env in (${labels.join(",")})` : undefined,
        next_token: nextToken,
      }
      const response = await this.apiClient.get("/orchestrator/jobs", {
        params,
      })
      return response.data as JobsResponse
    } catch (error) {
      console.error("An error occurred while listing jobs:", error)
      throw error
    }
  }

}

function getAPIConfig(
  property: "host" | "port" | "base",
  defaultValue: string
): string {
  const declared = document
    .querySelector(`link[rel=api-${property}]`)
    ?.getAttribute("href")
  const useDefault =
    declared === undefined ||
    declared?.match(/{{2}/) ||
    declared === "" ||
    declared === null
  return useDefault ? defaultValue : declared || ""
}

const host = getAPIConfig("host", document.location.hostname)
const port = getAPIConfig("port", "1234")
const base = getAPIConfig("base", "api/v1")
export const bacalhauAPI = new BacalhauAPI(
  `${document.location.protocol}//${host}:${port}/${base}`
)

msw handlers:

import { http, HttpResponse, RequestHandler, RequestHandlerOptions } from "msw";
import { TestData } from "../../basic/msw.tests";

export const jobsDashboardResponse = http.get('http://localhost:1234/api/v1/orchestrator/jobs', ({ cookies }) => {
  // Placeholders for messing around with cookies
  const { v } = cookies

  return HttpResponse.json(v === 'a' ? { foo: 'a' } : { bar: 'b' })
})

export const handlers: RequestHandler<any, any, any, RequestHandlerOptions>[] = [jobsDashboardResponse]

msw server:

import { setupServer } from "msw/node"
import { handlers } from "./handlers"

export const server = setupServer(...handlers)

The error:

  console.error
    An error occurred while listing jobs: AxiosError {
      message: 'Network Error',
      name: 'AxiosError',
      code: 'ERR_NETWORK',
      config: {
        transitional: {
          silentJSONParsing: true,
          forcedJSONParsing: true,
          clarifyTimeoutError: false
        },
        adapter: [ 'xhr', 'http' ],
        transformRequest: [ [Function: transformRequest] ],
        transformResponse: [ [Function: transformResponse] ],
        timeout: 0,
        xsrfCookieName: 'XSRF-TOKEN',
        xsrfHeaderName: 'X-XSRF-TOKEN',
        maxContentLength: -1,
        maxBodyLength: -1,
        env: { FormData: [Function], Blob: [class Blob] },
        validateStatus: [Function: validateStatus],
        headers: Object [AxiosHeaders] {
          Accept: 'application/json, text/plain, */*',
          'Content-Type': null
        },
        baseURL: 'http://localhost:1234/api/v1',
        params: {
          order_by: 'created_at',
          reverse: true,
          limit: 10,
          labels: undefined,
          next_token: undefined
        },
        method: 'get',
        url: '/orchestrator/jobs',
        data: undefined
      },
      request: XMLHttpRequest {
        open: [Function: open],
        setRequestHeader: [Function: setRequestHeader],
        send: [Function: send],
        abort: [Function: abort],
        getResponseHeader: [Function: getResponseHeader],
        getAllResponseHeaders: [Function: getAllResponseHeaders],
        overrideMimeType: [Function: overrideMimeType],
        onreadystatechange: [Getter/Setter],
        readyState: 4,
        timeout: [Getter/Setter],
        withCredentials: [Getter/Setter],
        upload: [Getter],
        responseURL: [Getter],
        status: [Getter],
        statusText: [Getter],
        responseType: [Getter/Setter],
        response: [Getter],
        responseText: [Getter],
        responseXML: [Getter],
        UNSENT: 0,
        OPENED: 1,
        HEADERS_RECEIVED: 2,
        LOADING: 3,
        DONE: 4
      }
    }

When I console.log or debug, it’s clearly getting grabbed by the MSW handler. So what’s up?

[1] Reactjs: MSW mock handlers failing with Error “Network request failed”

[2] FETCH_ERROR “TypeError [ERR_INVALID_URL]: Invalid URL” for requests made in tests

[3] Jest returns “Network Error” when doing a mock request with axios and msw

Colons in what looks like a JavaScript function call

This example is from an example in the video Vue Router 4 for Everyone at 1’37”. Notice (from the filename vite.config.js) that the context is JavaScript, not TypeScript.

export default defineConfig(config: {
  alias: {
    '@': path.resolve(pathSegments[0]: __dirname, pathSegments[1]: './src')
  },
  plugins: [vue()],
})

I am wondering: What is the semantics of the two colons in what looks like a call?

How do I best fix this issues where set state keeps adding 1 two times in my react native?

Why is the setPoints((prevPoint) => prevPoint + 1) in useEffect keeps adding 2 times almost immediately?

I’ve tried everything, how do I best fix this for it to print only once?

I am trying to check if the moving animation have gotten to a certain distance which is the value of distanceOfScreenTopToBigCircle, so I can add one to the point state, but it keeps adding 1 two times almost immediately.

const theBallPosition = new Animated.ValueXY({x: 0, y: 0});

const destinationY = distanceOfScreenTopToBigCircle ? distanceOfScreenTopToBigCircle : 0;

function movingBallFunction() {

  //const destinationY = ballAtTop ? distanceOfScreenTopToBigCircle : 0;


  //This is linear animation
  Animated.timing(theBallPosition, {
    toValue: {x: 0, y: destinationY},//This the distance the ball should fall to
    duration: movingBallTimeDuration,//This is for the time the ball should reach the bigCircle
    easing: Easing.linear,
    useNativeDriver: true,

  }).start();//This start() method starts our animation

  //This is to not show the instruction on how to start game when user
  //have started playing the game, or when the ball is moving already. .
  setShowHowToStartGameInstruction(false)
}

useEffect(() => {

  const animationListener = (value) => {

    if (value.y === distanceOfScreenTopToBigCircle) {

      console.log('it has reach the finals,', value.y)

      return setPoints((prevPoint) => prevPoint + 1);  

    }

  };

  // Attach the listener
  const listenerId = theBallPosition.addListener(animationListener);

  // Cleanup mechanism: remove the listener when the component unmounts
  return () => {
    theBallPosition.removeListener(listenerId);
  };

}, [theBallPosition, distanceOfScreenTopToBigCircle])

Click delete box to delete box and text using javascript

I have a shopping list, and next to each item there is a delete button. I want to click the button and remove the button and text next to it using javascript. I have tried the following but I have not had luck. I grabbed each button using document.getElementsByClassName(“delete”);, then added a click event to each using a for loop. I then created the remove function seen in the code that should delete the whole element on a click. Thanks.

html:

<html>
<head>
    <title>Javascript + DOM</title>
    <link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
    <h1>Shopping List</h1>
    <p id="first">Get it done today</p>
    <input id="userinput" type="text" placeholder="enter items">
    <button id="enter">Enter</button>
    <ul>
        <li class="italic" random="23">Notebook <button class="delete">Delete</button></li>
        <li class="bold red">Jelly <button class="delete">Delete</button></li>
        <li>Spinach <button class="delete">Delete</button></li>
        <li>Rice <button class="delete">Delete</button></li>
        <li>Birthday cake <button class="delete">Delete</button></li>
        <li>Candles <button class="delete">Delete</button></li>
    </ul>
    <script type="text/javascript" src="script.js"></script>
</body>
</html>

Javascript:

var button = document.getElementById("enter");
var input = document.getElementById("userinput");
var ul = document.querySelector("ul");
var li = document.getElementsByTagName("li");
var del = document.getElementsByClassName("delete");

function inputLength() {
    return input.value.length;
}

function createListElement() {
    var li = document.createElement("li");
    li.appendChild(document.createTextNode(input.value));
    ul.appendChild(li);
    input.value = "";
}

function addListAfterClick() {
    if (inputLength() > 0) {
        createListElement();
    }
}

function addListAfterKeypress(event) {
    if (inputLength() > 0 && event.keyCode === 13) {
        createListElement();
    }
}

function onOffClick(event) {
    this.classList.toggle("done");
}

function remove(event) {
    event.target.remove();
}

for (var i=0; i<li.length; i++) {
    li[i].addEventListener("click", onOffClick);
}

for(var i = 0; i < del.length; i++){
    del[i].addEventListener("click", remove);
}


button.addEventListener("click", addListAfterClick);

input.addEventListener("keypress", addListAfterKeypress);