Home > Blockchain >  ReactJS map: Expected an assignment or function call and instead saw an expression - no-unused-expre
ReactJS map: Expected an assignment or function call and instead saw an expression - no-unused-expre

Time:11-17

I'm in the midst of cleaning up errors for a repo and I've come across this error where someone's trying to to assign a tag value object to a const variable inside of a map function. Here's its current form:

const BatchEditState = {
    CURRENT: 'CURRENT',
    DELETE: 'DELETE',
    PUT: 'PUT',
}
handleShow = () => {
        this.batchEditSet = {};
        this.state.currentTags.map((tag) => {
            this.batchEditSet[tag.tag_name] = BatchEditState.CURRENT;
        });
    };

As far as I've researched, one is definitely not supposed to go about it this way even if it does still function. I've seen plenty examples returning a jsx element, but I'm pretty sure that's not the point for this. I do know a map function is supposed to at least return a value however.

I attempted to use a spread operator and an implicit return, but that didn't work out. I also tried making a basic return & even though I'm not encountering any immediate errors in our application, I'm still not sure if this is the right way to go. Still fairly new at this, but appreciate any info, help, and education I can get

handleShow = () => {
        this.batchEditSet = {};
        this.state.currentTags.map((tag) => {
            this.batchEditSet[tag.tag_name] = BatchEditState.CURRENT;
            return(
                BatchEditState.CURRENT
            )
        });
    };

CodePudding user response:

.map is only for creating new arrays by iterating over an existing array. While you want to iterate over an existing array, you don't want to create a new array - rather, you want to construct a plain object - so .map should not be used here. (The array you're constructing in your current code is going unused.)

To procedurally assign to properties of the object, do:

handleShow = () => {
  this.batchEditSet = {};
  this.state.currentTags.forEach((tag) => {
    this.batchEditSet[tag.tag_name] = BatchEditState.CURRENT;
  });
};

Or create an array of entries, then turn that array into an object.

handleShow = () => {
  this.batchEditSet = Object.fromEntries(
    this.state.currentTags.map(tag => [tag.tag_name, BatchEditState.CURRENT])
  );
};

But also, doing this.batchEditSet = in the first place looks like a mistake in React. If this is a component, you should almost certainly be calling this.setState instead of mutating the instance.

  • Related