Hi I am trying to pass params to backend from frontend using URLSearchParams to filter a list. The filtering did not happen without reloading the page because URLSearchParams wasn't updated. I wrote code as follows by searching the answers on this website but it still doesn't update. Please tell me what is wrong.
HomeScreens.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]]);
};
return (
<>
<Filterbar />
<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>
</>
);
}
jobActions.js
import axios from 'axios';
import {
JOB_LIST_REQUEST,
JOB_LIST_SUCCESS,
JOB_LIST_FAIL,
} from '../constants/jobConstants';
export const listJobs = (queryParams) => async (dispatch) => {
try {
dispatch({ type: JOB_LIST_REQUEST });
console.log(queryParams);
const { data } = await axios.get('/api/jobs', { params: queryParams });
dispatch({
type: JOB_LIST_SUCCESS,
payload: data,
});
} catch (error) {
dispatch({
type: JOB_LIST_FAIL,
payload:
error.response && error.response.data.message
? error.response.data.message
: error.message,
});
}
};
backend>controller>jobs.js
import ErrorResponse from '../utils/errorResponse.js';
import asyncHandler from '../middleware/async.js';
import Job from '../models/Job.js';
// @desc Get all jobs
// @routes GET /api/jobs
// @access Public
const getJobs = asyncHandler(async (req, res, next) => {
// let query;
// copy req.query
const reqQuery = { ...req.query };
// create query string
let queryStr = JSON.stringify(reqQuery);
// create operators ($gt, $gte, etc)
queryStr = queryStr.replace(
/\b(gt|gte|lt|lte|in)\b/g,
(match) => `$${match}`
);
// Finding resource
const jobs = await Job.find(JSON.parse(queryStr));
console.log(jobs);
res.json(jobs);
});
I just needed to add searchParams
in dependency array in useEffect to re-render whenever serchParams is changed. When I put queryParams
in the dep array I got indefinate loop, so I was confused, but searchParams
is working.
useEffect(() => {
dispatch(listJobs(queryParams));
}, [dispatch, searchParams]);