Home > Enterprise >  How to generate random words from an API?
How to generate random words from an API?

Time:01-05

I wrote this code :

export default class WordGenerator extends React.Component {
  state = {
    wordToShow : [test],
  }
  componentDidMount(){
    this.changeWordToShow()
  }

  changeWordToShow=()=>{
     fetch('https://random-word-api.herokuapp.com/word?lang=it').then(response=>this.setState({wordToShow: response}))
  }
  
  render(){
    return (
      <View style={Styles.container}>
        <Text style={Styles.paragraph}>
        {this.state.wordToShow[0]}
        </Text>
        <Button title="Change word" onPress={()=>this.changeWordToShow()}/>
      </View>
    );
  }
}

When I click myself on the link https://random-word-api.herokuapp.com/word?lang=it, I get an array containing one random italian word. However, when I press the button, the value of wordToShow seems to become null, as 'test' disappear with no italian words to replace it ...

CodePudding user response:

The response is in application/json, so it needs to be decoded first. Something like this:

changeWordToShow = () => {
  fetch('https://random-word-api.herokuapp.com/word?lang=it')
  .then((response) => response.json())
  .then((response) => this.setState({ wordToShow: response }));
};
  • Related