update Ok, so I've noticed that even though in isCategoryActive()
function I'm mutating only the variable newCategories
that was assigned a value from this.props.searchCategories
the searchCategories
prop changes value as well, therefore passing it to the consecutive array item's invocation of the isCategoryActive
function. Why is it happening though??update
I'm building a blog's frontend in React based on Wordpress REST API and I'm having problems creating links to filter posts categories after checking if they are already filtered. The problem I'm having is that even though I wrote a pure function isCategoryActive
inside the map function every consecutive category link url has every preceding category id in it. I would have thought that on every invocation of a pure function I would receive a clean result, but in my case it isn't like that. At the moment the wordpress stores 3 categories:
"uncategorized" with id: 1,
"javascript" with id: 4,
"third category" with id: 10
What I'm trying to get the console.log(newCategories, url) function inside the render() function to log:
[1] blog?categories=1
[4] blog?categories=4
[10] blog?categories=10
But at the moment it logs:
[1] blog?categories=1
[1,4] blog?categories=1,4
[1,4,10] blog?categories=1,4,10
I have no idea why it's keeping the record of the previous categories ids.
Here's the code:
// import dependencies
import React, { Component } from 'react'
import { Link } from 'react-router-dom'
import axios from 'axios'
// import components
import '../Styles/Css/PostsCategories.css'
import { createSearchUrl } from './SharedModules'
class PostsCategories extends Component {
constructor() {
super()
this.state = {
categories: null,
loading: false
}
}
componentDidMount() {
this.setState({
loading: true
})
axios.get(`http://localhost/wordpress-api/wp-json/wp/v2/categories`)
.then(res => {
this.setState({
categories: res.data,
loading: false
})
})
}
isCategoryActive = (category) => {
let newCategories = this.props.searchCategories
newCategories.indexOf(category) === -1
? newCategories.push(category)
: newCategories.splice(newCategories.indexOf(category),1)
return newCategories
}
render() {
if (this.state.loading || !this.state.categories) return <div className='posts-categories'><h2 className='loading'>Loading ...</h2></div>
const categories = this.state.categories.map(category => {
const newCategories = this.isCategoryActive(category.id)
const url = createSearchUrl('/blog', newCategories, this.props.searchString)
console.log(newCategories, url)
return (
<Link
to={url}
onClick={this.props.searchCategoryChange.bind(this, category.id)}
className='posts-category'
key={category.id} >
{category.name}
</Link>
)})
return (
<div className='posts-categories'>
{categories}
</div>
)
}
}
export default PostsCategories