In my application, I have a form that is supposed to search for the workout components that I have displayed based on two fields: category and difficulty. When I search, I can see that the URL changes properly, but the cards are not filtered at all. They disappear.
Below I have the code for the component where the search is made:
import React, {useState, useEffect} from 'react'
import {Container, Grow, Grid, Paper, AppBar,TextField,Button, TextareaAutosize} from '@material-ui/core';
import {useDispatch} from 'react-redux';
import {getWorkouts, getWorkoutsBySearch} from '../../actions/workouts';
import {useNavigate, useLocation, Navigate} from 'react-router-dom';
import ChipInput from 'material-ui-chip-input'
import Workouts from "../Workouts/Workouts";
import Pagination from '../Pagination';
import Form from "../Form/Form";
import useStyles from './styles';
function useQuery(){
return new URLSearchParams(useLocation().search);
}
function Home() {
const [currentId, setCurrentId]=useState(null);
const classes=useStyles();
const dispatch=useDispatch();
const query=useQuery();
const history=useNavigate();
const page=query.get('page') || 1;
const searchQuery=query.get('searchQuery');
const [search, setSearch] = useState('');
const [category, setCategory] = useState([]);
const searchWorkout=()=>{
if(search.trim() || category){
dispatch(getWorkoutsBySearch({search, category:category.join(',')}));
history(`/workouts/search?searchQuery=${search || 'none'} & category=${category.join(',')}`)
}else{
history(`/workouts`);
}
}
useEffect(()=>{
dispatch(getWorkouts());
},[currentId, dispatch]);
const handleKeyPress=(e)=>{
if(e.keyCode===13){
searchWorkout();
}
}
const handleAdd=(categ)=>setCategory([...category,categ]);
const handleDelete=(categoryToDelete)=>setCategory(category.filter((categ)=>categ!==categoryToDelete));
const user = JSON.parse(localStorage.getItem("profile"));
return (
<Grow in>
<Container maxWidth="xl">
<Grid className={classes.gridContainer} container justifyContent="space-between" alignItems='stretch' spacing={3}>
<Grid item xs={12} sm={6} md={9}>
<Workouts setCurrentId={setCurrentId}/>
</Grid>
<Grid item xs={12} sm={6} md={3}>
<AppBar className={classes.appBarSearch} position="static" color="inherit">
<TextField
name="search"
variant="outlined"
label="Search workouts"
onKeyPress={handleKeyPress}
fullWidth
value={search}
onChange={(e)=>setSearch(e.target.value)}
/>
<ChipInput
style={{margin:'10px 0'}}
value={category}
onAdd={handleAdd}
onDelete={handleDelete}
label="Search Category"
variant="outlined"
/>
<Button onClick={searchWorkout} className={classes.searchButton} variant="contained" color="primary">Search</Button>
</AppBar>
{
user?.result?.email.endsWith('admin.com')?
<>
<Form currentId={currentId} setCurrentId={setCurrentId}/>
<Paper className={classes.pagination} levation={6}>
<Pagination/>
</Paper>
</>
:<></>
}
</Grid>
</Grid>
</Container>
</Grow>
)
}
export default Home
Here I have the actions code that is supposed to handle the workouts loading on the page.
import { FETCH_ALL, FETCH_BY_SEARCH, CREATE, UPDATE, DELETE, LIKE, COMMENT_WORKOUT, COMMENT_MEAL, MARK_WORKOUT_AS_COMPLETE, GET_USER_DATA } from '../constants/actionTypes';
import * as api from '../api';
export const getWorkouts=()=> async (dispatch)=>{
try{
const data=await api.fetchWorkouts();
dispatch({type:FETCH_ALL,payload:data});
}catch(error){
console.log(error);
}
}
export const getWorkoutsBySearch=(searchQuery)=>async(dispatch)=>{
try{
const {data: {data}}=await api.fetchWorkoutsBySearch(searchQuery);
dispatch({type:FETCH_BY_SEARCH,payload:data});
}catch(error){
console.log(error);
}
}
export const createWorkout=(workout)=>async(dispatch)=>{
try{
const data=await api.createWorkout(workout);
dispatch({type:CREATE,payload:data});
}catch(error){
console.log(error.message);
}
}
export const updateWorkout=(id,workout)=>async(dispatch)=>{
try{
const data=await api.updateWorkout(id,workout);
dispatch({type:UPDATE,payload:data})
}catch(error){
console.log(error);
}
}
export const deleteWorkout = (id) => async (dispatch) => {
try {
await api.deleteWorkout(id);
dispatch({ type: DELETE, payload: id });
} catch (error) {
console.log(error);
}
};
export const likeWorkout=(id)=>async(dispatch)=>{
try{
const data=await api.likeWorkout(id);
dispatch({type:LIKE,payload:data})
}catch(error){
console.log(error);
}
}
export const postCommentOnWorkout=(data)=>async(dispatch)=>{
try{
const res=await api.postCommentOnWorkout(data);
dispatch({type:COMMENT_WORKOUT,payload:res})
}catch(error){
console.log(error);
}
}
export const markWorkoutAsComplete=(data)=>async(dispatch)=>{
try{
const res=await api.markWorkoutAsComplete(data);
dispatch({type:MARK_WORKOUT_AS_COMPLETE,payload:res})
}catch(error){
console.log(error);
}
}
export const postCommentOnMeal=(data)=>async(dispatch)=>{
try{
const res=await api.postCommentOnMeal(data);
dispatch({type:COMMENT_MEAL,payload:res})
}catch(error){
console.log(error);
}
}
export const getUserDetails=()=>async(dispatch)=>{
try{
dispatch({type:GET_USER_DATA})
}catch(error){
console.log(error);
}
}
The reducer for this action is this one:
case FETCH_BY_SEARCH:
return action. payload;
The back-end code with the requests from the backend is this one:
import express from "express";
import mongoose from "mongoose";
import WorkoutMessage from "../models/workoutMessage.js";
import User from "../models/user.js";
const router = express.Router();
export const getWorkouts = async (req, res) => {
try {
const workoutMessages = await WorkoutMessage.find();
res.status(200).json(workoutMessages);
} catch (error) {
res.status(404).json({ message: error.message });
}
};
export const getWorkoutsBySearch = async (req, res) => {
const { searchQuery, category } = req.query;
try {
const difficulty = new RegExp(searchQuery, "i");
const workouts = await WorkoutMessage.find({ $or: [ { category }, { difficulty } ]});
res.json({ data: workouts });
} catch (error) {
res.status(404).json({ message: error.message });
}
}
export const createWorkout = async (req, res) => {
const workout = req.body;
const newWorkoutMessage = new WorkoutMessage({
...workout,
creator: req.userId,
createdAt: new Date().toISOString(),
});
try {
await newWorkoutMessage.save();
res.status(201).json(newWorkoutMessage);
} catch (error) {
res.status(409).json({ message: error.message });
}
};
export const updateWorkout = async (req, res) => {
const { id: _id } = req.params;
const workout = req.body;
if (!mongoose.Types.ObjectId.isValid(_id))
return res.status(404).send(`No workout with that ${_id}`);
const updatedWorkout = await WorkoutMessage.findByIdAndUpdate(
_id,
{ ...workout, _id },
{ new: true }
);
res.json(updateWorkout);
};
export const deleteWorkout = async (req, res) => {
const { id } = req.params;
if (!mongoose.Types.ObjectId.isValid(id))
return res.status(404).send("No workout with that id");
await WorkoutMessage.findByIdAndRemove(id);
res.json({ message: "Workout deleted successfully" });
};
export const likeWorkout = async (req, res) => {
const { id } = req.params;
if (!req.userId) return res.json({ message: "Unauthenticated" });
if (!mongoose.Types.ObjectId.isValid(id))
return res.status(404).send("No workout with that id");
const workout = await WorkoutMessage.findById(id);
const index = workout.likes.findIndex((id) => id === String(req.userId));
if (index === -1) {
workout.likes.push(req.userId);
} else {
workout.likes = workout.likes.filter((id) => id != String(req.userId));
}
const updatedWorkout = await WorkoutMessage.findByIdAndUpdate(id, workout, {
new: true,
});
res.json(updatedWorkout);
};
export const commentOnWorkout = async (req, res) => {
const { userId, workoutId, userName, comment } = req.body;
const workout = await WorkoutMessage.findById(workoutId);
if (workout) {
User.findOne({ _id: userId }).then(async (user) => {
if (user) {
const commentObject = {
commentedBy: userId,
commentor: userName,
comment: comment,
};
const updatedWorkout = await WorkoutMessage.updateOne(
{ _id: workoutId },
{
$push: {
comments: commentObject,
},
}
);
const workouts = await WorkoutMessage.findById(workoutId);
res.send({ data: workouts });
}
});
}
};
export const markWorkoutAsComplete = async (req, res) => {
const { userId, workoutId, status } = req.body;
console.log("MARK AS complete API hit", status);
await User.findOneAndUpdate({ _id:userId},
{
$set: {
completedWorkouts: {
status: status,
workoutId:workoutId
},
},
},
{ upsert: true }
);
const user2 = await User.findById(userId);
console.log(user2)
res.send({ data: user2 });
};
export default router;
I cannot see where the problem is coming from. Could you help me solve this?