Source:  Twitter logo

I used to fetch data in my components, but now I learned about higher order components i'm trying to refactor my code to use hoc for data fetching;

from the original component how to move url that i am getting from routers props to hoc wrapper

 state = { details: [], loading: true };

 componentDidMount() {
  fetch(this.props.match.url)
   .then(res => res.json())
   .then(data => this.setState({ details: data, loading: false }))
}

how do i pass this.props.match.url to export default withData(App, __here__) ?

withData:

export const withData = (ComposedComponent, url) => {
  return class WithData extends Component {
  state = { data: [], loading: false };

  componentDidMount() {
    this.setState({ loading: true });
    fetch(url)
     .then(response => response.json())
     .then(data => this.setState({ loading: false, data }));
  } 

  render() {
    return <ComposedComponent {...this.state} {...this.props} />;
  }
 };
};

In that case you don't need to pass anything to HOC, HOC is just a function that is returning a react component. Component will receive the props, you can access them by this.props. Access the url by the same way this.props.match.url.

Ultimately you are rendering a react component returned by HOC for a particular path, so component will receive the props in the same way.

Like this:

export const withData = (ComposedComponent) => {
  return class WithData extends Component {

    state = { data: [], loading: false };

    componentDidMount() {
      this.setState({ loading: true });
      fetch(this.props.match.url);
       .then(response => response.json())
       .then(data => this.setState({ loading: false, data }));
    } 

    render() {
      console.log('this.props', this.props);
      return <ComposedComponent {...this.state} {...this.props} />;
    }

  };
};

Working Example.

0 users liked answer #0dislike answer #00
Mayank Shukla profile pic
Mayank Shukla

Copyright © 2022 QueryThreads

All content on Query Threads is licensed under the Creative Commons Attribution-ShareAlike 3.0 license (CC BY-SA 3.0).