javascriptreactjsobjecturlsearchparams

Finding a key by its value in JavaScript returns undefined


I am trying to delete a key and a value that I got using useSearchParams() hook in React Router v6 by clicking "remove" button on a filtered value. I need to find a key by its value, so I coded as follows but it returns "undefined" key in console. I refered this answer from this website but it doesn't work. Please help!

HomeScreen.js

import React, { useEffect } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { useSearchParams } from 'react-router-dom';
import Filterbar from '../components/Filterbar';
// import PhotosnapIcon from '~/images/photosnap.svg';
import { listJobs } from '../actions/jobActions';

import './HomeScreen.scss';

export default function HomeScreen() {
  const dispatch = useDispatch();

  const jobList = useSelector((state) => state.jobList);
  const { loading, error, jobs } = jobList;

  let [searchParams, setSearchParams] = useSearchParams();

  const params = [];

  searchParams.forEach((value, key) => {
    params.push([key, value]);
  });

  const queryParams = new URLSearchParams(params);

  const url = new URL(window.location.href);
  window.history.pushState(null, null, url);

  useEffect(() => {
    dispatch(listJobs(queryParams));
    console.log(jobs);
  }, [dispatch]);

  const addQuery = (key, value) => {
    setSearchParams((prev) => [...prev.entries(), [key, value]]);
  };

  const deleteQuery = (value) => {
    const key = Object.keys(searchParams).find(
      (key) => searchParams[key] === value
    );
    searchParams.delete(`${key}`);
    console.log(key);
    setSearchParams(searchParams);
  };

  return (
    <>
      <Filterbar queryParams={queryParams} deleteQuery={deleteQuery} />
      <ul>
        {jobs.map((job) => (
          <li className={job.featured ? 'post featured' : 'post'} key={job._id}>
            <div className="post__img-container">
              <img src={job.logo} alt="photosnap" />
            </div>
            <div className="post__upper-container">
              <div className="post__company-container">
                <h2 className="post__company">{job.company}</h2>
                {job.new && <span className="post__label new">new!</span>}
                {job.featured && (
                  <span className="post__label featured">featured</span>
                )}
              </div>
              <h3 className="post__job-title">{job.position}</h3>
              <div className="post__data">
                <span className="post__date">{job.postedAt}</span>
                <div className="post__dot"></div>
                <span className="post__hours">{job.contract}</span>
                <div className="post__dot"></div>
                <span className="post__location">{job.location}</span>
              </div>
            </div>
            <div className="post__lower-container">
              <button
                className="post__category"
                name="role"
                value={job.role}
                onClick={(e) => addQuery('role', e.currentTarget.value)}
              >
                <span>{job.role}</span>
              </button>{' '}
              <button
                className="post__category"
                value={job.level}
                onClick={(e) => addQuery('level', e.currentTarget.value)}
              >
                <span>{job.level}</span>
              </button>
              {job.languages.map((language) => (
                <button
                  className="post__category"
                  name="language"
                  value={language}
                  onClick={(e) => addQuery('languages', e.currentTarget.value)}
                >
                  <span>{language}</span>
                </button>
              ))}
              {job.tools.map((tool) => (
                <button
                  className="post__category"
                  name="tool"
                  value={tool}
                  onClick={(e) => addQuery('tools', e.currentTarget.value)}
                >
                  <span>{tool}</span>
                </button>
              ))}
            </div>
          </li>
        ))}
      </ul>
    </>
  );
}

Filterbar.js

import './Filterbar.scss';

export default function Filterbar({ queryParams, deleteQuery }) {
  const filterValues = Array.from(queryParams.values());

  return (
    <div className="filter">
      <div className="filter-container">
        {filterValues.map((filterValue) => (
          <div className="filter-item" key={filterValue}>
            <span className="filter-name">{filterValue}</span>
            <button className="remove-btn">
              <img
                src="/icon-remove.svg"
                alt="remove"
                onClick={(filterValue) => deleteQuery(filterValue)}
              />
            </button>
          </div>
        ))}
      </div>
      <button className="clear-btn">Clear</button>
    </div>
  );
}

Solution

  • I found a solution by myself! I added idx in onClick on remove button in Filterbar.js, and wrote code in the deleteQuery function as follows in HomeScreen.js.

    HomeScreen.js

    const deleteQuery = (idx) => {
        const keyArray = Array.from(queryParams.keys());
        const key = keyArray[idx];
        queryParams.delete(`${key}`);
        setSearchParams(queryParams);
      };
    

    Filterbar.js

    <button className="remove-btn">
       <img
        src="/icon-remove.svg"
        alt="remove"
        onClick={() => deleteQuery(idx)}
       />
    </button>