Search code examples
react-nativeimagerenderingfetch-api

Despite I get different values of images in base64 when fetching data, but the same image is output for all images when rendering


I have a server where I store user images in base64 format. Im trying to fetch and render it, but I keep getting the same image. I understand that the problem is most likely in the particular work of react, but I don't understand what exactly the problem is.

Here's what I tried:

I have class Viewer that renders components Dialog with different props "name"

class Viewer extends Component {
      render() {
        return (
          <View>
            <Dialog name={'0'} id={'0'}/>
            <Dialog name={'54353'} id={'54353'}/>
            <Dialog name={'54354'} id={'54354'}/>
          </View>
        );
      }
}

In Dialog I have method getImage that fetch data in base64 and when componentDidMount setting it to "img"

componentDidMount(){
    this.img = this.getImage(this.name);
}

getImage(_id) {
        //this.setState({ loading: true });
        const fileBlob = new FileReader(); // BLOB
        /*this.setState({ 
          loading: true
        });*/
        fetch(domenName + '/server/getUserImageById.php?user_id=' + _id)
          .then(response => response.blob())
          .then(response => {
              this.loading = false;
              this.setState({loading: false});
              response.size == 0 ? img = domenName + '/assets/img/noimage.png':
                [fileBlob.readAsDataURL(response), fileBlob.onload = () => {
                  //console.log(this.loading);
                  img = fileBlob.result;
                  //console.log("id:" + _id);
    
                }]
          }).catch(error => {
            this.loading = false;
            //this.setState({loading: false});
            //console.log('error') 
          })
        return img;
}

Despite I get different values of images in base64 when fetching data, but the same image is output for all images when rendering

Output

    class Dialog extends Component {
      render(){
        console.log(this.loading);
    
        if(this.loading){
          return (
            <View>
              <Text>Loading...</Text> 
              <Text>Im user №{this.id}!</Text> 
            </View>    
          );
        }
        else{
          return (
            <View>
              <Image 
                key = {this.id}
                source={{uri: this.img}} 
                style={{ width: 60, height: 60, borderRadius: 30 }} 
              />
              <Text>Im user №{this.id}!</Text> 
            </View>    
          );
        }
      }
    }

Link to sandbox with example: https://snack.expo.dev/@konst1966/ea6dad


Solution

  • Solved the problem by moving the fetch() function to componentDidMount. Also adding to .then(response)=>{} this code:

    
        this.setState({image:img})