reactjsreact-reduxreact-redux-form

Calling API and passing data to another component


I am working on react application in which I need to call the API with press of a button and the API response should be transferred to the second component along with displaying the content of second component. How can I do that ?


Solution

  • One way to do this would be to hold the fetched data inside state and pass it as a property to a child component which is conditionally rendered.

    Function Components

    import React, {useState} from 'react'
    
    class ParentComponent {
      state = {
       data: undefined
    }
      const handleClick = async () => {
        //fetchData
    this.setState({data: fetchedData})
      };
    
      return (
        <div>
          <button onClick={this.handleClick}>Click me </button>
          {this.state.data && <Child data={this.state.data} />}
        </div>
      );
    };
    
    const Child = (props) => {
      return (
        //render data
        <div>{props.data}</div>
      );
    };
    
    

    Class Components

    import React from "react";
    
    class ParentComponent extends React.Component {
      state = {
        data: undefined,
      };
      handleClick = async () => {
        //fetchData
        this.setState({ data: fetchedData });
      };
      render() {
        return (
          <div>
            <button onClick={this.handleClick}>Click me </button>
            {this.state.data && <Child data={this.state.data} />}
          </div>
        );
      }
    }
    
    class Child extends React.Component {
      render() {
        return (
          //render data
          <div>{this.props.data}</div>
        );
      }
    }