0

I have an array of 16 objects and I use "number" prop to cut unwanted elements. So if I want an array of 8 elements I would type:

<Images number="8"/>

However my useEffect does not run after initial render, but only after I make a change in the array later on, this returns all 16 elements, if I make a typo, wait for a bug screen to render and fix a typo, my browser shows 8 elements as it should. This is the rest of my code:

const Images = (props) => {
    const [deck, setDeck] = useState(data);
    // data.length is equal 16

    const sliceDeck = () => {
        data.splice(parseInt(props.number, 10), data.length)
    }
    
    useEffect(()=>{
        sliceDeck()
        setDeck(data)
    }, [])

    return (
        <>
        <div className="img-container">
           {deck.map(object => <div className="img-on" key={object.id}><img src={object.src} alt=""/></div>)}
        </div>

        </>
    );
  }
  
  export default Images;

1 Answer 1

1

You need to add props.number to the dependency array to make sure it runs every time there is an update to it

const Images = (props) => {
    const [deck, setDeck] = useState(data);
    
    useEffect(()=>{
      if(!isNaN(props?.number)){
        const temp = data.splice(parseInt(props?.number, 10), data.length)
        setDeck(temp)
      }
    }, [props?.number])

    return (
        <>
          <div className="img-container">
            {deck.map(object => <div className="img-on" key={object.id}>
              <img src={object.src} alt=""/>
            </div>)}
          </div>
        </>
    );
  }
  
  export default Images;

emphasized text

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.