Search code examples
reactjsamazon-s3aws-lambdareact-component

Don't remount component but change values


I have a component which is rendering some values with image id of the s3 bucket. have created one child component which will call to aws server and get image URL. have set loader until API call is in progress. after URL will be received from the call, the loader will stop and an image will be rendered.

Problem: i have some operation on values to be performed. like maintaining values, increment-decrements.

while updating states, a component will be remount. and again image API will be called and loaded.

shouldComponentUpdate won't work. because if I will use it, it will not display changes on the screen.

have set loader till image loads. but it's not a valid thing to show loader on each button click. looking for some better solution. stuck on the issue from past 12 hours. will be really thankful if someone can help me to get rid of this.

Thank You.


Solution

  • I think the issues is in the componentWillReceiveProps method within <LoadImage />

    componentWillReceiveProps(nextProps){
            if (this.props !== nextProps) {
                this.setState({
                    image:DefaultImage,
                    loading:true
                })
                this._loadImages(nextProps)
            }else{
                this.setState({
                    loading: false,
                })
            }
        }
    

    You are calling this._loadImages(nextProps), which can be called again and again as props are passed into from the owner component.

    Even though you are doing a comparison on the incoming props, this.props !== nextProps will always be true because they are both objects. You can see some questions on this.

    You will be better doing comparisons on the particular props you are concerned with - if this is the way you want to go.

    Also to be noted componentWillReceiveProps is deprecate, you should look into getDerivedStateFromProps. View the docs here.