Why Isn't may Array of image SRC's are not updating with UseState

I am trying to make an app where you can click on an anchor point on a page, then click on an image in a side div and change the anchor point’s image src to be that of the new image clicked. I have an array of image SRC’s that I map through, however when I manipulate this array and run it through useState, but the images do not update while the array of locations does. The images render correctly on first render, but do not re-render after calling useState.

This is the current State of the relevant code

let anchorsImages = useMemo(() => [
        beads[0].image,
        beads[0].image,
        beads[0].image,
        beads[0].image,
        beads[0].image,
        beads[0].image,
        beads[0].image,
        beads[0].image,
        beads[0].image,
        beads[0].image,
        beads[3].image,
    ],[])

    let indexOfCurrentAnchor = null

   const [anchorsState, setAnchorsState] = useState(anchorsImages)

   useEffect(() => {
         setAnchorsState(anchorsImages)
   },[anchorsImages])

   const changeBead = (bead) => {
        anchorsImages[indexOfCurrentAnchor] = bead
        setAnchorsState(anchorsImages)
        console.log(anchorsImages)
    }

    const changeAnchor = (index) => {
        indexOfCurrentAnchor = index
    }
<div className="left">
                    {beads.map((bead, index) => {
                        return <img src={bead.image} key={Math.floor(Math.random()*1000)} className='bead' alt="Jewelry" onClick={()=>{changeBead(bead.image)}}/>
                    })}
                   </div>
                   <div className="middle">
                         <img src={mannequin} id='mannequin' className='img' alt="Jewelry"/>
                         <img src={chain}  id="chain" className='img' alt="chain"/>
                         <div className='anchors'>
                         {anchorsState.map((anchor, index) => {
                            return <img src={anchor} key={Math.floor(Math.random()*1000)} className={'anchor'+" "+"anchor"+index} alt="Jewelry" onClick={()=>{changeAnchor(index)}}/>
                        })}
                         </div>
                         
                   </div>

changeAnchor is successfully changing the index, changeBead is changing the correct bead in anchorsImages/AnchorsState, however the application is not rendering the changes.

>Solution :

  1. anchorsImages should not be memoized

  2. You should not be using random numbers for key=

  3. Anchor index should be stored in react state

If you provide a working sandbox then it will be easier to point out the exact changes required.

Leave a Reply