user3498459
user3498459

Reputation:

Why will JavaScript filter method not work in React?

So I have a function that has to basically update a list of categories. It is invoked by a lifecycle method. However, for some reason the function returns the same array as it was before.

Let me show you the function:

getCategoriesNotCurrent = () => {

    this.setState({categoriesNotCurrent:this.state.categories.filter(category=>category!==this.state.currentCategory)},()=>{console.log(`STATE HERE ${this.state.currentCategory}`)});

}

Also, let me show you where I am using it to render elements...

<select className="catsteps" id="catstep3">
            {this.state.categoriesNotCurrent.length>0
                ?
                this.state.categoriesNotCurrent.map((x,i)=>
                    <option key={i} value={x.category} id={x.category}>{x.category}</option>
                )
                :
                true
            }  
 </select>

Would really appreciate any help...

Here is some code that explains how this function is invoked through a lifecycle method. In fact it's a two step process. A lifecycle method will invoke another function, which will invoke this function.

    componentWillMount() {

        Axios.post(`http://localhost:3001/mongooose/getCategories`,{'user':this.props.currentUser})
          .then(data=>{
            this.setState({categories:data.data},()=>

(this.getRecipesForDefault()));
          })
          .catch(err=>console.log(err))
    }

ABOVE is the lifecycle method. It invokes the below function, which will invoke the function that is not working.

getRecipesForDefault = () => {
        this.setState({currentCategory:'default'},()=>
            {
                Axios.post(`http://localhost:3001/mongooose/retrieveSavedRecipes`,{'user':this.props.currentUser,'category':this.state.currentCategory})
                     .then(data=>{data.data.length>0?this.setState({recipesRetrieved:data.data},()=>(this.getCategoriesNotCurrent()))
                                                    :(this.setState({recipesRetrieved:[]},()=>{
                                                        alert('No recipes found for this category. Please choose a different category.')
                                                    }))
                                                })  
                     .catch(err=>console.log(err))
            }
        )
    }

Upvotes: 0

Views: 424

Answers (1)

Janiis
Janiis

Reputation: 1576

If your state looks like this (my mockup).

state = {
    currentCategory: "Second category",
    categoriesNotCurrent: [],
    categories: [
      { category: "First category" },
      { category: "Second category" },
      { category: "Third category" }
    ]
  };

Then filter should be updated to (used prettier to make more readable code):

getCategoriesNotCurrent = () => {
    const categoriesNotCurrent = this.state.categories.filter(category => {
      return category.category !== this.state.currentCategory;
    });

    this.setState(
      {
        categoriesNotCurrent
      },
      () => {
        console.log(`STATE HERE ${this.state.currentCategory}`);
      }
    );
  };

This way, the "Second category" will be filtered out.

You should use category.category !== this.state.currentCategory; in filter.

Upvotes: 0

Related Questions