I'm looking to add a filterPost feature to my React blog posts

As I am exploring the implementation of a filterPost feature using react and redux in my blog post, I encountered an issue. When attempting to create a function where users can click to list posts in a filter array, I faced an error that I have been trying to resolve. Being relatively new to React, I am working on strengthening my understanding of it.

import { createSlice } from "@reduxjs/toolkit";

const initialState = {
    topics: [
      { id: 1, title: "An Introduction to React", category: "React" },
    ],
    filterPosts: [],
  };

const searchSlice = createSlice({
    name:"topic",
    initialState,
    reducers: {
        filterTopics(state, action){
            state.filterPosts = state.topics.filter((post)=>post.category === action.payload)
        }
    }
})

export const {filterTopics} = searchSlice.actions

export default searchSlice.reducer

This is the search details.

import React from 'react'

export default function SearchDetails({categoryChangeHandler,currentCategory}) {
    const {topics} = useSelector(state=>state.search)
    console.log(topics)

    const categories = []
    
    topics.map(post=>categories.push(post.category))

    const categoryFinal = ["All categories", ...new Set(categories)]

  return (
    <ul className="list-group">
      {categoryFinal.map((category) => (
        <li
          key={category}
          className={
            category === currentCategory
              ? "list-group-item active"
              : "list-group-item"
          }
          onClick={() => categoryChangeHandler(category)}
        >
          {category}
        </li>
      ))}
    </ul>
  )
}
import React, { useState } from 'react'
import { useDispatch } from 'react-redux'
import { useState } from 'react'
import searchPost from '../../store/search-post'
import SearchDetails from './SearchDetails'

export default function SearchFilter() {
    const [filter, setFilter] = useState(false)
    const [currentCategory, setCurrentCategory ] = useState("")
    const dispatch = useDispatch()

    const categoryHandlerChanger = (category) =>{
        setCurrentCategory(category)
        if(category === "All category"){
            setFilter(false)
        
        }else{
            dispatch(filterTopics(category))
            setFilter(true)
        }
    }
  return (
    <div>

        <searchPost filter={filter}/>
        <SearchDetails 
        currentCategory={currentCategory}
        categoryHandlerChanger={categoryHandlerChanger}

        />
    </div>
  )
}
export default function SearchPost({filter}) {
    const {topics} = useSelector(state=>state.search)
    const {filterTopics} = useSelector(state=>state.search)

    console.log(topics)
  return (
    <div>
      <p>{filter ? filterTopics.length : topics.length} of the {topics.length} posts</p>
      {!filter && topics.map((post)=>(
        <article key={post}>
            {post.title}

        </article>
      ))}

{filter && filterTopics.map((post)=>(
        <article key={post}>
            {post.title}

        </article>
      ))}
    </div>
  )
}
SearchDetails.js:26 
        
       Uncaught TypeError: categoryChangeHandler is not a function
    at onClick (SearchDetails.js:26:1)
    at HTMLUnknownElement.callCallback (react-dom.development.js:4164:1)
    at Object.invokeGuardedCallbackDev (react-dom.development.js:4213:1)
    at invokeGuardedCallback (react-dom.development.js:4277:1)
    at invokeGuardedCallbackAndCatchFirstError (react-dom.development.js:4291:1)
    at executeDispatch (react-dom.development.js:9041:1)
    at processDispatchQueueItemsInOrder (react-dom.development.js:9073:1)
    at processDispatchQueue (react-dom.development.js:9086:1)
    at dispatchEventsForPlugins (react-dom.development.js:9097:1)
    at react-dom.development.js:9288:1

Answer №1

An error has been detected in the code related to SearchFilter. It seems that you are passing the function as categoryHandlerChanger, but the component SearchDetails is expecting categoryChangeHandler.

Remember: it's handlerChanger versus changeHandler :)

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The MIME type 'text/html' is incompatible with stylesheet MIME type and is not supported

I have exhausted all possible solutions for the issue, from specifying the type for <link rel="stylesheet" href="./style.css" /> to using app.use(express.static('public')), but unfortunately, none of them seem to resolve the problem. index ...

Issue with Stack Divider not appearing on Chakra UI card

I'm currently designing a card element using Chakra UI. However, I've noticed that the Stack Divider in the Card Body isn't displaying as expected. Is there a specific way it needs to be structured for it to show up? For example, should I se ...

The React-Toastify module is missing

Having issues with react toast plugin displaying an error. Prior to attempting to use the toast feature, I executed this command: npm install --save react-toastify The following error is being shown in Google Chrome Console: ERROR in ./src/Pages/Login ...

Attempting to display a singular form

Currently, I am working on a MERN app and encountering a small issue... I am developing an application where users can create rooms and within those rooms, they can plan their daily activities. It's similar to a TODO app but more intricate. I wanted ...

Passing current data into a predefined function using useCallback in React

Currently, I'm using Next.js and React to develop an application where I am facing a challenge with opening a model using a function while passing data from the current state. I have been able to fetch updated data from my Supabase database successful ...

What is the best way to implement a sidebar closing animation?

Utilizing both react and tailwindcss, I successfully crafted a sidebar menu that elegantly appears from left to right when the user clicks on the hamburger icon. However, my attempts to create a reverse animation as the sidebar disappears from right to lef ...

I'm experiencing issues with my local host. Can someone please assist me with troubleshooting?

Currently I am developing a restaurant website using Reactjs. Everything was going smoothly until I encountered an error message while running "npm start" in localhost. Instead of displaying my website, the browser is showing me an error stating page unres ...

Encountering a hiccup while trying to install dependencies, neither the --force nor --legacy-peer-deps flags have been

Embarking on a new project with React, I encountered an error while attempting to install the dependencies outlined in the tutorial video I am following. Unfortunately, I'm uncertain how to resolve this issue on my own. The list of dependencies and c ...

Testing Content Rendered in a Modal or Popover using React, Jest, and Material-UI

Some material-ui components, such as Dialog and Menu, do not render their results in the same location as where they are placed by their parent component. Due to this behavior, testing for the presence of content within these components becomes challengin ...

What is the best way to retrieve and save the titles of checked boxes in the Autocomplete using state with hooks?

I've implemented the React Material-UI Autocomplete feature with checkboxes in my project. Here is what I have so far in my code (check out demo.js for details): https://codesandbox.io/s/material-demo-rxbhz?fontsize=14&hidenavigation=1&theme=d ...

Tips for disabling linting for legitimate useEffect instances?

Below is the correct useEffect code snippet: useEffect(() => { if (state.companyId !== undefined && state.companyId === -1) { return; } if (accessNotesRef.current) { accessNotesRef.current.focus(); } if (vinR ...

React is unable to access the value of a JSON local file within a component

I'm currently working on extracting a value from a local json file. Despite no errors, the value is not displaying when viewed in the browser. Initially, I am utilizing a local json file, but I plan to switch to an endpoint in the future. Within Hea ...

What benefits does React offer that jQuery does not already provide?

What sets ReactJS apart from jQuery? If jQuery can already handle everything, why should we use React? I've tried to research on Google but still don't have a clear answer. Most explanations focus on terms like "views," "components," and "state" ...

Display a component by selecting a hyperlink in React

Currently working on a story in my storytelling, which might not be too important for the question I have. What I am trying to accomplish is creating a scenario where there is an anchor tag that, once clicked, triggers the opening of a dialog box or modal ...

Error message: When trying to refresh a Next.js page, a ReferenceError occurs because the document

Currently, I am in the process of developing a straightforward UI library using React for Next.js 9.4. Here is a snippet of what I have implemented: // input.js in React UI Lib import React from "react"; import styled from "./input.module.scss"; const I ...

I'm having trouble getting my search program to function properly with React

I have recently started learning React and I am currently working on a basic program that searches the GitHub API to retrieve repository names and URLs. Unfortunately, I'm experiencing some issues with getting it to function properly. In a previous ve ...

What is the best way to retain the default value of an MUI form field in Mongoose database?

I am experiencing an issue with my small nextjs app that utilizes an MUI form. The form consists of 2 fields: a default field and an email field. While the email field saves correctly to the database, I am facing difficulties saving the defaultValue field ...

Encountering a problem when trying to utilize material-ui icons in a React application

After installing the Material-UI core and icons packages using npm install @material-ui/core and npm install @material-ui/icons in my React app, I tried to use the FileUploadIcon. Here's how I imported it: import { FileUploadIcon } from '@materia ...

How can React Native efficiently retrieve data from multiple APIs simultaneously?

In my current project, I am incorporating multiple APIs that are interlinked with each other by sharing the same data structure... Below is the code snippet: export default class App extends React.Component { constructor(props) { super(props); } ...

Guide to creating a unique React component for displaying a single popup upon clicking with the ability to pass props to it

As someone who is still learning React, I decided to challenge myself by creating a Jeopardy game using this framework. My current idea is to have a popup appear when a player clicks on a box on the Jeopardy board, displaying the clue associated with that ...