ReactJS display fetch response onClick

I am not quite sure if I understood you correctly... but since you're adding your fetch inside a react extended class, you can render it inside the home component like so:

  state = {
    visible: false
  }

  generateItem() {
    if (this.state.visible) {
      return <ItemLister />
    }
    return <h2>nothing to show</h2>
  }

  render() {
    return(
      <div>
        <button onClick={() => this.setState({visible: true})}>Click</button>
        {this.generate()}
      </div>
    )
  }

The onClick function will update the state every time the user clicks on it and a new rerender will occur thus calling generateItem again with a new random word.

Hope this is what you were searching for.


I would say that you move your fetch logic to home component and maintain a state in home component just like you are doing in Itemlister component. Then all you have to do is pass your state to Itemlister component. Your home component will look like this

export class Home extends React.Component {
constructor(props) {
    super(props)
    this.state = {suggestion: ""}
    ...
}

componentDidMount(){
  // For initial data
  this.fetchData();
}

fetchData = () => {
  fetch("......./suggestions/random", {
    method: "GET",
    dataType: "JSON",
    headers: {
      "Content-Type": "application/json; charset=utf-8",
    }
  })
  .then((resp) => {
    return resp.json()
  }) 
  .then((data) => {
    this.setState({ suggestion: data.suggestion })                    
  })
  .catch((error) => {
    console.log(error, "catch the hoop")
  })
}

render() {
    return (
        ...
                <tbody >
                   // Pass state to itemlister like this
                    <tr><td><ItemLister suggestion={this.state.suggestion}/></td></tr>
                </tbody>
            </table>
            <div className="container center">
                // Add event handler here. On every click it will fetch new data
                <button onClick={this.fetchData}>GENERATE</button>
                <button>SAVE</button>
                <button>MATCH</button>
            </div>
        </div>
    )
  }
}

And your ItemLister component has the responsibility to display the data via props.

export class ItemLister extends React.Component {
    constructor() {
    super();
    }

    render() {
    return(
      <h2> 
        {this.props.suggestion}
      </h2>
      )
     }
    } 

As per the suggestion by dubes in comment, If you don't want to maintain any state in this component then you can make this functional component like this

function ItemLister(props) {
  return <h2> 
            {props.suggestion}
          </h2>;
}

Tags:

Fetch

Reactjs