Angel Christy
Angel Christy

Reputation: 55

Next JS doesnt re render element when state changed

i have a code where im fetching the image name

const [foundImg, setFoundImg] = useState(false)
var imgNames = []
---
axios.get('http://someapi.com')
.then(res => {
  imgNames.push(res.data)
  setFoundImg(true)
}.catch(err => console.log(err)

And i put this condition in the return / render

         { (foundImg === true) 
            ? itemImg.map( i => {
              return <div className="product--box">
                <Image width={50} height={50} src='/public/dummy.png' className='img'/>
              </div>
            })
            : null
          }

But the problem is, when the imagenames are fetched, the component doesnt re render. So it is still empty now. How can i make it so that this image are rendered when the fetching returns data?

Upvotes: 3

Views: 18198

Answers (2)

Quang Th&#225;i
Quang Th&#225;i

Reputation: 697

You are storing imgNames as a local variable, and because it is not a state of react component, so that if you change imgNames, React wont recognize that you need to update the component.

Solution:

Change var imgNames = [] become to const [imgNames, setImgNames] = useState([])

Then change imgNames.push(res.data) to setImgNames(res.data)

After the state changes, React will re-render the component for you

Upvotes: 5

Sonu Nigam
Sonu Nigam

Reputation: 277

you should use imgNames.map() instead of item.Img.map()

Upvotes: 0

Related Questions