Home > Mobile >  Extract the assignment of "numberImg" from this expression. sonarlint(Javascript:S1121)
Extract the assignment of "numberImg" from this expression. sonarlint(Javascript:S1121)

Time:12-16

import React, { useState } from "react";
import arrowRight from "../images/arrowRight.svg";


function Slider({ images }) {

    let [showPicture, setShowPicture] = useState(0);
    let numberImg = images.length;

    const imgPrevious = () => {
        if (showPicture === 0) {
            setShowPicture(numberImg - 1);
        } else {
            setShowPicture(showPicture - 1);
        }
        return (setShowPicture);
    };

    const imgNext = () => {
        if (showPicture === numberImg - 1) {
            setShowPicture(numberImg = 0); // the problem is here

        } else {
            setShowPicture(showPicture   1);
        }
        return (setShowPicture);
    };

    return (
        <div className="carrousel">
            {
                numberImg > 1 && <img className="arrow arrow-left" src={arrowRight} alt="previous" onClick={imgPrevious} />
            }
            {
                images.map((image, index) => {
                    return (
                        <img key={index} className={index === showPicture ? 'carrousel-img actif' : 'carrousel-img'} src={image} alt="Lodging" />
                    )
                })
            }
            {
                numberImg > 1 && <img className="arrow arrow-right" src={arrowRight} alt="next" onClick={imgNext} />
            }
        </div>
    );
}

export default Slider;

Hi there, I have a small problem with "sonarlint" (see the title) The problem lies with "numberImg =0" in the imgNext function.

I am currently making a slider

this one works very well, but I would have liked to know why sonarlint indicates to me a problem on the equality

Any ideas ? Thanking you.

CodePudding user response:

Extract the assignment of "numberImg" from this expression.

This is pretty straightforward, there's nothing ambiguous about it:

// Change this
setShowPicture(numberImg = 0);

// to this
numberImg = 0;
setShowPicture(numberImg);

CodePudding user response:

I would have liked to know why sonarlint indicates to me a problem on the equality

setShowPicture(numberImg = 0);

It's not an equality. It's an assignment. Code quality tools don't like it when you do assignments inside function calls. It's not very readable, and you might mistake assignments for comparisons.

In the words of SonarSource itself:

Assignments within sub-expressions are hard to spot and therefore make the code less readable. Ideally, sub-expressions should not have side-effects.

SonarLint wants you to write:

numberImg = 0;
setShowPicture(numberImg);
  • Related