0

In below code what happening is concat is replacing the value in array instead of pushing it in react.

export default class Newsfeed extends Component {

 constructor(props, context) {
 super(props, context);
 this.imagemodal = this.imagemodal.bind(this)
 this.state = {
   imageArray:[],
   myimage:[{id:1,media:[{url:xyz},{url:abc}},
           {id:2, media:[{url:xyz}, {url:abc}]
  }




 this.state.myimage.map((myimage) => {
    if(someId === myimage.id){

     myimage.media.map((media)=>{

        this.setState({
          imageArray:this.state.imageArray.concat([media.url]),
          showimageslider:true,
          sid:sid
        },() =>console.log(this.state.imageArray.length))
      })

    }
  })

imageArray is over writing the array instead of concatenating it

Help me in this reagards..

2 Answers 2

1

setState function is asynchronous. You can try something like below

let mediaURLs = [];
this.state.myimage.map((myimage) => {
    if(someId === myimage.id){
      myimage.media.map((media)=>{
          mediaURLs.push(media.url);      
      })
    }
})
mediaURLs = mediaURLs.concat(this.state.imageArray);
this.setState({
  imageArray:mediaURLs,
  showimageslider:true,
  sid:sid
},() =>console.log(this.state.imageArray.length))
Sign up to request clarification or add additional context in comments.

1 Comment

Why don't you use 'forEach' instead of 'map'. It might work a little faster.
0

Since the seState function is asynchronous you need to do the normal operation -> form the array and then do setState

const imageArray = [];
this.state.myimage.map((myimage) => {
if(someId === myimage.id){

 myimage.media.map((media)=>{
    imageArray.push(media.url);  
  }
});
this.setState({
      imageArray:this.state.imageArray.concat(imageArray),
      showimageslider:true,
      sid:sid
    },() =>console.log(this.state.imageArray.length))
  })

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.