After puppeteer infinite scroll finishes does not return all results

Here is the code in my data scraping file:

const puppeteer = require('puppeteer');
const db = require('../db');
const Job = require('../models/job');

(async() => {
  try {
    const browser = await puppeteer.launch({
      headless: false,
      defaultViewport: null,
      // args: ['--no-zygote', '--no-sandbox']
    });
    const url = 'https://www.linkedin.com/jobs/search?keywords=Junior%20Software%20Developer&location=Indianapolis%2C%20IN&geoId=&trk=homepage-jobseeker_jobs-search-bar_search-submit&position=1&pageNum=0';

    // Open browser instance
    const page = await browser.newPage({
      waitUntil: 'networkidle0'
    });
    console.log(`Navigating to ${url}`);
    await page.goto(url);

    // Scroll to bottom of page, click on 'See More Jobs' and repeat   
    let lastHeight = await page.evaluate('document.body.scrollHeight');
    const scroll = async() => {
      while (true) {
        await page.evaluate('window.scrollTo(0, document.body.scrollHeight)');
        await page.waitForTimeout(2000);
        let newHeight = await page.evaluate('document.body.scrollHeight');
        if (newHeight === lastHeight) {
          console.log('Done scrolling!');
          break;
        }
        lastHeight = newHeight;
        seeMoreJobs();
      }
      console.log(data);
    }
    // Click on 'See More Jobs'
    const seeMoreJobs = async() => {
      await page.evaluate(() => {
        document.querySelector('button[data-tracking-control-name="infinite-scroller_show-more"]').click();
      });
    }
    // Collect data
    const data = await page.evaluate(() => {
      const allJobsArr = Array.from(document.querySelectorAll('a[data-tracking-control-name="public_jobs_jserp-result_search-card"]'));
      const namesAndUrls = allJobsArr.map(job => {
        return {
          name: job.innerText,
          url: job.href,
          path: job.pathname
        }
      });
      return namesAndUrls;
    });
    scroll();
  } catch (err) {
    console.log(err);
  }
})();

So the above code is designed to navigate to the variable ‘url’ and then to scroll until the scroll function “breaks”/finishes, i.e., to the very bottom of the page. Once these actions have finished, I want to then log some data in the form of an array with three properties from each job posting: name, href, and path. When I run the IIFE as shown I am able to grab the first 24-25 job postings with my ‘data’ function, which are the first to be displayed on page load (before any of the scrolling takes place). For whatever reason, this ‘data’ function is unable to evaluate the entire page or document after all the scrolling has occurred. I have tried various things and have really analyzed what the code is doing, but alas, I am at a loss for a solution. My end goal here is to comb through every job posting that has displayed with my scrolling function and then to log everything (not just the first 24-25 results) returned with the desired data properties to the console.

Thanks, all.

React useEffect causing function to run 7 times. I am using a useCallback but it still runs to many times

The updateAddedState function with the console.log(“running”) is running 7 times on a page refresh/initial render.

I only want the updateAddedState function to run once when the addedItems state updates.

I only what the useEffect to run when the actual addedItems state has changed. What am I doing wrong??

export const DropdownMultiSelect = ({
  data,
  placeholder,
  updateState,
}: IProps) => {
  const [searchTerm, setSearchTerm] = useState<string>("");
  const [filteredData, setFilteredData] = useState<IData[]>(data);
  const [addedItems, setAddedItems] = useState<IData[]>([]);
  const [placeholderValue, setPlaceholderValue] = useState<string>("");
  const [inputActive, setInputActive] = useState<boolean>(false);

  const onFocus = () => setInputActive(true);
  const onBlur = () => {
    setInputActive(false);
  };

  const updateAddedState = useCallback(() => {
    console.log("running");
    
    updateState(addedItems);
  }, [updateState, addedItems]);

  const handleFilter = (e: React.ChangeEvent<HTMLInputElement>) => {
    setSearchTerm(e.target.value);
  };

  const handleFilterData = useCallback(
    (searchTerm: string) => {
      let newFilter = data.filter((value) => {
        return value.name.toLowerCase().includes(searchTerm.toLowerCase());
      });

      for (let i = 0; i < addedItems.length; i++) {
        for (let j = 0; j < newFilter.length; j++) {
          if (addedItems[i].id === newFilter[j].id) {
            newFilter.splice(j, 1);
          }
        }
      }

      setFilteredData(newFilter);
    },
    [addedItems, data]
  );

  const addItem = (value: IData) => {
    setAddedItems([...addedItems, value]);
    setSearchTerm("");
    handleFilterData("");
    setInputActive(false);
  };

  const removeItem = (value: IData, e: React.MouseEvent) => {
    e.preventDefault();
    let newArray: IData[] = [];

    for (let i = 0; i < addedItems.length; i++) {
      newArray.push(addedItems[i]);
    }

    for (let i = 0; i < newArray.length; i++) {
      if (value.id === newArray[i].id) {
        newArray.splice(i, 1);
      }
    }
    setAddedItems(newArray);
    setInputActive(true);
  };

  useEffect(() => {
    if (addedItems.length === 1) {
      setPlaceholderValue(`${addedItems.length} vald`);
    } else if (addedItems.length > 1) {
      setPlaceholderValue(`${addedItems.length} valda`);
    } else {
      setPlaceholderValue(placeholder);
    }
  }, [addedItems, placeholderValue, placeholder]);

  useEffect(() => {
    handleFilterData(searchTerm);
  }, [searchTerm, addedItems, handleFilterData]);

  useEffect(() => {
    let isMounted = true;
    if (isMounted) {
      if (addedItems) {
        updateAddedState();
      }
    }

    return () => {
      isMounted = false;
    };
  }, [updateAddedState, addedItems]);

  return (
    <div id="dropdownMulti">
      <section className="inputSection">
        <input
          type="text"
          placeholder={placeholderValue}
          className="inputSection__input"
          onChange={handleFilter}
          value={searchTerm}
          onFocus={onFocus}
          onBlur={onBlur}
        />
        <div className="inputSection__icon-container">
          {inputActive ? (
            <AiOutlineUpCircle
              onClick={() => setInputActive(false)}
              className="inputSection__icon-container--up"
            />
          ) : (
            <AiOutlineDownCircle className="inputSection__icon-container--down" />
          )}
        </div>
      </section>
      <section className="addedItems-section">
        {inputActive &&
          addedItems.map((addedItem) => {
            return (
              <div className="addedItem" key={addedItem.id}>
                <p className="addedItem__item">{addedItem?.name}</p>
                <button
                  data-testid="remove-btn"
                  className="addedItem__button"
                  onMouseDown={(e: React.MouseEvent) =>
                    removeItem(addedItem, e)
                  }
                >
                  <AiOutlineCloseCircle />
                </button>
              </div>
            );
          })}
      </section>
      {inputActive && (
        <ul className="dataResult">
          {filteredData.slice(0, 10).map((value) => {
            return (
              <li
                className="dataResult__item"
                key={value.id}
                tabIndex={0}
                onMouseDown={() => addItem(value)}
              >
                {value.name}
              </li>
            );
          })}
        </ul>
      )}
    </div>
  );
};


Any tips on how to cut the number of times it runs?

CSS :not(:first-of-type) isn’t working on div but works on other elements

I am creating an accordion in which the first element is open. Crediting the code here.

The main modification to this code is that I wanted to put some subtext under the main title, so I created a div and wrapped the h2 and h3 inside of it. You can see my HTML, CSS, and JS below:

$(function() {
  $(".accordion-content:not(:first-of-type)").css("display", "none");
  $(".js-accordion-title:first-of-type").addClass("open");

  $(".js-accordion-title").click(function() {
    $(".open").not(this).removeClass("open").next().slideUp(300);
    $(this).toggleClass("open").next().slideToggle(300);
  });
});
.accordion-container div.accordion-content:first-of-type {
  background: red;
}

.accordion-title {
  border-top: 1px solid #BEBEBE;
  padding: 2em 0;
  background: #F7F7F7;
}

.accordion-container .accordion-title h2  {
  position: relative;
  margin: 0;
  background-color: #F7F7F7;
  font-size: 32px;
  font-weight: 700;
  text-transform: uppercase;
  color: #DA15B6;
  text-align: center;
  cursor: pointer;
  margin-bottom: .125em;
}

.accordion-container .accordion-title h3 {
  background-color: #F7F7F7;
  font-size: 18px;
  letter-spacing: 0.9px;
  line-height: 1.5em;
  font-weight: 600;
  text-transform: uppercase;
  color: #000;
  text-align: center;
}

.price-number {
  font-size: 25px;
  letter-spacing: 0.54px;
  font-weight: 700;
}

.accordion-container .accordion-title h2::after {
  content: '3';
  position: absolute;
  right: 25px;
  bottom: -10px;
  font-size: 1.3em;
}
.accordion-container .accordion-title.open h2::after {
  content: '2';
  position: absolute;
  right: 25px;
  bottom: -10px;
  font-size: 1.3em;
}

/*CSS for CodePen*/

.accordion-content {
  padding-left: 2.3125em;
}
.accordion-container {
  width: 100%;
  margin: 0 auto;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="accordion" class="accordion-container">
  <div class="accordion-title js-accordion-title">
    <h2 class="price-plan-name">Standard</h2>
    <h3 class="starting-price">Starting at
      <span class="price-number">$1,650</span></h3>
  </div>
  <div class="accordion-content">
    <p>Accordion Content1</p>
  </div>
  <div class="accordion-title js-accordion-title">
    <h2>Pro</h2>
    <h3 class="accordion-subtitle">Starting at
      <span class="price-number">$2,950</span></h3>
  </div>
  <div class="accordion-content">
    Accordion Content2
  </div>
  <div class="accordion-title js-accordion-title">
    <h2>Elite</h2>
    <h3 class="accordion-subtitle">Starting at
      <span class="price-number">$3,950</span></h3>
  </div>
  <div class="accordion-content">
    Accordion Content3
  </div>
</div>

The issue I am having is trying to have the first accordion-content opened on page load. This should be achievable with the first line of JS, “$(“.accordion-content:not(:first-of-type)”).css(“display”, “none”);” but it doesn’t seem to work. I believe it has to do with a conflict between the div “accordion-title” and div “accordion-content”. If I change “accordion-content” to have a p or h5 tag for example, the code will work properly. Are there any suggestions on how I could work around this?

Thanks in advance.

function doesnt give the appropriate output

The following function seems to give the appropriate output but when I import the same function to the other component, the function just gives a blank output. I think there happens to be a problem with the return statement.
P.S: What I’m trying to make is an online judge where user can input their solution and then we will test their function with some test cases we have defined.

const javascriptRunner = (fileLocation, input) => {
  //judge functionality

  // let output = ''
  import(`../codes/${fileLocation}`).then((f) => {
    console.log(
      'output:',
      f.default(...input),
      'type:',
      typeof f.default(...input),
      'for input :',
      input
    )
    return f.default(...input)
  })

How do I use kotlin for firebase cloud functions?

Is there a way I can use kotlin for firebase cloud functions??
I’m currently working on a project like uber and running out of time seriously, I’m familiar with kotlin but know nothing about JavaScript or type script.

I really would love it if it’s possible to do it with kotlin

Two JavaScript funtions “await” for something that will resolve, is there any way to avoid it?

I’ve to admin I need to read more about this topic. Anyways, here is the background:

  1. foo and bar need to use instance, which is a result of a async call
  2. load is checking if instance is undefined, to avoid re-loading it

Example:

let instance;

// Will resolve in 5 seeconds when instance is undefined
async load() {
  if ('undefined' !== typeof instance) {
    return;
  }

  instance = await new Promise(resolve => setTimeout(() => {
    resolve([]);
  }, 5000));
}

async foo() {
  await load();

  // Use instance
}

async bar() {
  await load();

  // Use instance
}

Timeline:

  • foo() will be called after 1 seconds (say t1)
  • bar() will be called after 3 seconds (say t3)

Conclusions:

  • load() will resolve at t6 (t1 + t5) for the first time
  • load() will resolve at t8 (t3 + t5) for the second time
  • Any call to load() after t6 will return immediately (that’s what I want in the first place)
  • There is no way to avoid the second load()

So to the question: is there any way to avoid the second load() (and the second resolve of the promise)? Note that foo and bar will be invoked by a framework, so I cannot “control” their invocation.

Requiring Semicolons in Javascript Visual Studio 2019

I am trying to check my javascript line endings for semicolons visual studio 2019 EsLint. I added the following line to the .eslintrc file under the rules object:

"semi": [2, "always"]

However, Visual Studio still does not check for semicolons. Am I doing something wrong? any suggestions?

Changing style color via JavaScript isn’t working

I have been trying to change the style color of an input field when a certain option is selected but it is not working. I have tried both onclick and oninput but to no avail. I suspect the issue lies with {{ type }} or == ‘Buy’.

function changeColor () {
    var transaction_type = document.getElementById('buysell');
    var option_user_selection = transaction_type.options[ transaction_type.selectedIndex ].text;
    if (option_user_selection == 'Buy') {
        document.getElementById('costb').style.color = '#006400';
    }
    else {
        document.getElementById('costb').style.color = '#DC143C';
    }
}
<div class="transaction_type">
     <p>Transaction Type:</p>
     <select style="font-size:16px" class="form-select" id='buysell' required>
           {% for type in form.transaction_type %}
               <option>{{ type }}</option>
           {% endfor %}
     </select>
</div>

forms.py

transaction_choices = [
    ('BUY', 'Buy'),
    ('SELL', 'Sell'),
]
transaction_type = forms.CharField(
    max_length=4,
    widget=forms.Select(
        choices=transaction_choices,
        attrs={
            'class': 'form-select',
            'name': 'transaction_type',
            'id': 'floatingTransaction',
            'oninput': 'changeColor();'
        })
)

cost_basis = forms.DecimalField(
    min_value = 0,
    widget = forms.NumberInput(attrs={
            'class': 'form-control',
            'name': 'cost_basis',
            'id': 'costb',
        })
)

PrimeNG Drag&drop tree

I using p-tree component in my application and I need to implement drag&drop feature. I tried with PrimeNG drag&drop module but it does not met my expectations, I’m looking for something like this: example.
Is this achivable on p-tree component, i tried to implement this in plain JS with using this tutorial but I’m struggling with these container relations. My code is the same like in tutorial but for containers and draggables I’m using this

const draggables = this.treeEl?.nativeElement.querySelectorAll('li');
const containers = this.treeEl?.nativeElement.querySelectorAll('p-treenode');

Why is the button colour being affected by the background?

I have a site with a gradient background. That works fine. But, when I add a button to it, the colour changes to the one on the background. This is my CSS:

BTW, open the snippet on full-page, or it won’t look clear

const leftSide = document.getElementById("playerLeft");
const rightSide = document.getElementById("playerRight");
const newGame = document.getElementById("newGame");

function setSelectedPlayer(position) {
    switch (position) {
        case 1:
            rightSide.style.backgroundColor = "#ffffff80"
            leftSide.style.backgroundColor = "#fff"
            break;
        case 2:
            leftSide.style.backgroundColor = "#ffffff80"
            rightSide.style.backgroundColor = "#fff"
            break;
    }
}

newGame.onpointerdown = function () {
    newGame.style.top = "10px";
}

newGame.onpointerup = function () {
    newGame.style.top = "-10px";
}
<!DOCTYPE html>
<html>

<head>
    <title>Pig Game!</title>

    <style>
        body {
            background-image: linear-gradient(90deg, hsla(217, 100%, 50%, 1) 0%, hsla(186, 100%, 69%, 1) 100%);
            align-items: center;
            font-family: sans-serif;
        }

        #parent {
            height: 70%;
            width: 70%;
            opacity: 30%;
            position: absolute;
            top: 20%;
            bottom: 0;
            left: 0;
            right: 0;
            margin: auto;
        }

        #title {
            color: white;
            position: absolute;
            top: 10%;
            bottom: 0;
            left: 0;
            right: 0;
            margin: auto;
            text-align: center;
            font-size: 250%;
        }

        #playerLeft {
            width: 50%;
            height: 100%;
            border-radius: 10px 0 0 10px;
            float: left;
        }

        #playerRight {
            width: 50%;
            height: 100%;
            border-radius: 0 10px 10px 0;
            float: left;
        }

        .activePlayer {
            background-color: rgba(255, 255, 255, 1);
        }

        .inActivePlayer {
            background-color: rgba(255, 255, 255, 0.5);
        }

        .button {
            border-radius: 40px;
            border-color: white;
            border-style: solid;
            position: absolute;
            top: 0;
            bottom: 0;
            left: 0;
            right: 0;
            width: 20%;
            height: 10%;
            margin: auto;
            background-color: white;
        }
    </style>
</head>

<body>

    <h1 id="title">Pig Game!</h1>

    <div id="parent">
        <div class="activePlayer" id="playerLeft">

        </div>

        <div class="inActivePlayer" id="playerRight">

        </div>

        <button type="button" class="button buttonNewGame" id="newGame">Hi</button>
    </div>

    <script src="script.js"></script>
</body>

</html>

And the button with the text hi is not appearing white. Why is that so? And how can I make it white?

How to redirect to another site automatically in Next.js

I am trying to make my progressive web app automatically redirect to another site when the user clicks on the icon on their desktop.

As of right now when the user clicks on the icon it opens up a landing page where the user can link on the link to be redirected.

I’m using Next.js and JavaScript. I appreciate any help you can give me.

An error occur while deploying at vercel Error: Command “npm install” exited with 1 with sanity client

It seems I’ve run into a problem while deploying my project on Vercel, it is a react(next js) app created with “create-next-app” when running the app on “localhost:3000” it runs fine, every component, client and cms is working fine but when deploying it on the Vercel during the building process it gives an error which has to do something with sanity client which I can’t figure out. The link to the repository: Project’s Repository

Here are the logs during the building process of Vercel.
(please help this newbie, figure this out).


[17:52:52.260] Cloning github.com/Hritik-Jaiswal/Electronic-store-project (Branch: main, Commit: c8daae8)
[17:52:52.891] Cloning completed: 630.486ms
[17:52:53.027] Installing build runtime...
[17:52:55.264] Build runtime installed: 2.237s
[17:52:55.592] No Build Cache available
[17:52:55.845] Installing dependencies...
[17:52:57.758] npm ERR! code ERESOLVE
[17:52:57.761] npm ERR! ERESOLVE unable to resolve dependency tree
[17:52:57.761] npm ERR! 
[17:52:57.762] npm ERR! While resolving: [email protected]
[17:52:57.762] npm ERR! Found: @sanity/[email protected]
[17:52:57.762] npm ERR! node_modules/@sanity/client
[17:52:57.762] npm ERR!   @sanity/client@"^3.2.0" from the root project
[17:52:57.762] npm ERR! 
[17:52:57.762] npm ERR! Could not resolve dependency:
[17:52:57.762] npm ERR! peer @sanity/client@"^2.11.0" from [email protected]
[17:52:57.763] npm ERR! node_modules/next-sanity-image
[17:52:57.763] npm ERR!   next-sanity-image@"^3.2.1" from the root project
[17:52:57.763] npm ERR! 
[17:52:57.763] npm ERR! Fix the upstream dependency conflict, or retry
[17:52:57.763] npm ERR! this command with --force, or --legacy-peer-deps
[17:52:57.763] npm ERR! to accept an incorrect (and potentially broken) dependency resolution.
[17:52:57.764] npm ERR! 
[17:52:57.764] npm ERR! See /vercel/.npm/eresolve-report.txt for a full report.
[17:52:57.764] 
[17:52:57.764] npm ERR! A complete log of this run can be found in:
[17:52:57.765] npm ERR!     /vercel/.npm/_logs/2022-07-07T12_22_56_098Z-debug-0.log
[17:52:57.778] Error: Command "npm install" exited with 1

Filtering the data through multiple filters – JS

I have multiple filters like this

const [filters, setFilters] = useState({
    model: [],
    color: [],
    location: [],
    rating: 0,
});

And I have a list of bikes, which should be filtered. Their array of objects looks like this

bikes = [{
  model: "Nissan",
  color: "Red",
  location: "New York",
 },
 {
  model: "Honda",
  color: "Blue",
  location: "New York",
}...]

I might have multiple values for each filter, like color: ["Red", "Green"] and model: ["Ducati", "Nissan"]. In that case, I should show all red and green bikes from Ducati and Nissan.

How can I do this in JS.

Cross checking data within the same dataset

I am trying to figure out the best way to achieve something. I make a database query that returns a lot of data

const [data] = await dbConnection.execute(
  'SELECT * FROM data WHERE timestamp >= DATE(NOW() - INTERVAL 1 WEEK)',
);

The data it returns is a mismatch of events, at this moment in time, I am interested in two event types; email.delivered and interaction.click. This is some sample where the name is the event type.

[
    {
    name: 'email.delivered',
    programme: 'Email One',
    timestamp: 2022-03-24T18:06:02.000Z,
    "payload":{
          "id":"bcabca7c-a5d5-4e02-b247-2292240ffc77",
      },
    },
    {
    name: 'interaction.click',
    programme: 'Email One',
    timestamp: 2022-03-24T18:06:02.000Z,
    "payload":{
        "correlation":{
           "channel":"email",
           "messageId":"bcabca7c-a5d5-4e02-b247-2292240ffc77",
        },
        "metadata":{
            "customerId":"9999999111",
            "programName":"Email One"
        }
      },
    },
    ...
]

What I essentially want to know is this, for each programme, how many emails were delivered and how many clicks were there. So I produced this

const dataReduced = data.reduce((acc, o) => {
    const name = o.name?.replace('email.', '').replace('interaction.', '');
    if (!acc[o.programme]) {
        acc[o.programme] = {
            delivered: 0,
            click: 0,
        };
    }
    acc[o.programme][name] = (acc[o.programme][name]) + 1;
    return acc;
}, {});

I have set up a JSFiddle to demonstrate

This all works fine, however, I now need to somehow get more granular. I only want programmes from the last 1 week, hence my sql statement having an INTERVAL. This works fine for delivered, as I know the timestamp relates to the event.

However, clicks are different. I could click on an email link today which would make it show in my report, however, that email programme could have been delivered months ago.

I now essentially only want to include clicks if their parent programme was delivered within the last 1 week.

To do this, from the click event, I would need to obtain the payload.correlation.messageId. I would then need to cross check this against the payload.id from all delivered events to find a match and then check the timestamp of that delivered event. If the
timestamp is within a week, then include the click, if not, ignore it.

How could something like this be achieved?

Thanks

How to test handleSubmit of a form in react with jest

I have the following form (taken some inputs out to make a bit more readable):


function App() {
  const [firstName, setFirstName] = useState("");
  const [lastName, setLastName] = useState("");

  const handleSubmit = async (event: React.FormEvent<HTMLFormElement>) => {
    event.preventDefault();
    // Submits form data to API 
  };

  return (
    <FormContainer className="Form">
      <form onSubmit={handleSubmit} data-testid="form">
        <span>First Name</span>
        <Input
          type="text"
          onChange={(e) => setFirstName(e.target.value)}
          value={firstName}
          data-testid="first-name-input"
        />
        <span>Last Name</span>
        <Input
          type="text"
          onChange={(e) => setLastName(e.target.value)}
          value={lastName}
          data-testid="last-name-input"
        />
        <div>
          <Button testID="submit-button" type="submit">
            Submit
          </Button>
        </div>
      </form>
    </FormContainer>
  );
}

export default App;

  

I just want to test that the handleSubmit function is called (for now). I’ve written the following test:

test("handleSubmit is called when form submitted", async () => {
  render(<App />);
  const handleSubmitMock = jest.fn();

  fireEvent.submit(screen.getByTestId("form"));

  await waitFor(() => {
    expect(handleSubmitMock).toHaveBeenCalled();
  });
});

However I’m getting an error that it received 0 calls.

Is there a way to check that the handleSubmit is called with this component?