David Geismar
David Geismar

Reputation: 3422

React Native: Cant rerender Image after state change

I am starting with react-native. I am requesting a gif from the giphy API and then updating my giphyUrl in state (the state is changed) but the gif doesnt change ( the component is not rerendered).

class QuoteList extends Component {
  state = { quotes: [],
            giphyUrl: 'https://media.giphy.com/media/nZQIwSpCXFweQ/giphy.gif'
          };

  componentWillMount() {
    console.log('Again?')
    axios.get('https://api.tronalddump.io/search/quote?query='+this.props.characterName)
      .then(response => this.setState({ quotes: response.data._embedded.quotes }))
    this.getGiphy()
  }

  getGiphy() {
    console.log('getgif')
    const GiphyUrl = "https://api.giphy.com/v1/gifs/search?api_key=tutu&limit=1&q=" + this.props.characterName.replace(" ", "+");
    console.log(GiphyUrl)
    axios.get(GiphyUrl)
      .then(response => {
                  console.log(response)
                  console.log(response.data.data[0].url)

                  this.setState({ giphyUrl: response.data.data[0].url })
                  console.log(this.state)
                })

  }

  renderQuotes() {
    return this.state.quotes.map(
      quote => <QuoteDetail key={quote.quote_id} quote={quote}/>
    );
  }
  render() {
    return (
      <ScrollView>
      <Image
        source={{uri: this.state.giphyUrl}}
        style={styles.gifStyle}
      />

        {this.renderQuotes()}
      </ScrollView>
    );
  }
}

Why is the component not rerendering ? when I console.log the state in the callback of the axios request, I can see that the state is changed. Even when I try to "force" rerender (forceUpdate), it wouldnt rerender.

Upvotes: 4

Views: 4406

Answers (2)

houssameddin
houssameddin

Reputation: 33

Adding the key prop to any view will cause a rerender of the view as long as the key is changing.

Upvotes: 3

M Reza
M Reza

Reputation: 19708

Try updating the key property of the image:

<Image
    source={{uri: this.state.giphyUrl}}
    key={this.state.giphyUrl}
    style={styles.gifStyle}
/>

Upvotes: 14

Related Questions