Home > Net >  setState inside map and filter
setState inside map and filter

Time:09-02

I am recently learning the map and filter method in react native and I have a question. After finding a particular row of my array (with filter), how do I set only a particular field of that specific row? I have

this.state = {
  post: [{ id: "0", author: "Duffy Duck", delay: "1", picture: "" }]
}
putpicture(id) {
  const picture_new = "/gggg(yyb45789986..."
  const data = this.state.post
    .filter((item) => item.author == id)
    // my error is here. How can i put picture_new const, inside post.picture?
    .map((pictures) => this.setState({ post.picture: picture_new }))
}  

Now i want setState inside map and filter for every post. i want this output:

id:"0", author:"Duffy Duck",delay:"1", picture:"/gggg(yyb45789986..."

How can i do?

CodePudding user response:

This doesn't 100% make sense to me - are you sure you want to set all pictures on posts by an author at once? Is the post array meant to hold multiple posts? It looks like that's the goal based on the code, so I'll answer that as is.

You're close to a solution - the things you're missing are

  1. .map is called with an item the same way .filter is
  2. Don't setState during the map - in fact .map should ideally never have side effects. It's more efficient to call setState once with your new data.
putpicture(id) {
  const picture_new = "/gggg(yyb45789986...";
  const data = this.state.post
    .filter((item) => item.author == id)
    .map((item) => {
      // .map changes the array one item at a time
      // return the original item (...item) but with the `picture` property modified
      // the result gets stored in the data object above
      return { ...item, picture: picture_new }
    });
  // now that you have the modified array, put it into state
  this.setState({ post: data });
}

CodePudding user response:

In case you can have more than one post in array and anything apart of post in you state:

putpicture(id) {
    const picture_new = "/gggg(yyb45789986...";
    // create new variable
    const newPost = this.state.post.reduce((res, it) => {
        // update only one item
        res.push(it.author === id ? {...it, picture: picture_new} : {...it});

        return res;
    }, []);
    // use destructuring and previous state to update the state 
    this.setState(prev => {...prev, post: newPost});
}
  • Related