Reuse a method from another component

  • A+

I would like to pass the both states as the result of getSettings method in Settings component to Add component. Is there any way to do that without copying the method to the other component?

Thank you

Settings component

export class Settings extends Component {     constructor(props) {         super(props);          this.state = {          languages: [],          currencies: []         };     }      getSettings() {         fetch('/settings', {             method: 'get',             headers: {                 'Accept': 'application/json',                 'Content-Type': 'application/json'             }         })         .then( ... )         .then(json => {             this.setState({                 currencies: json.currencies,                 languages: json.languages             });         })     } } 

Add component

export class Add extends Component {     displayName =  constructor(props) {     super(props);      this.state = {     languages: [],     currencies: []     }; } 


Excuse my impassioned plea, but for the love of all that is sacred please don't use higher order component abstractions, render props, etc. This is a simple problem that deserves a simple solution. No magic required. No esoteric React knowledge required.

  1. Refactor getSettings function out of components.
  2. Make getSettings function accept a component parameter.
  3. Inside getSettings function, replace all use of 'this' with the 'component' parameter
  4. Import getSettings function into any component that will use it.
  5. Pass the component instance to this function. Eg. getSettings(this)
  6. Congratulations, you now have a reusable and independently testable function that any component (or anything else for that matter) can use as required.

    const getSettings = component => () => {   // Do your fetch here, and in your last   // .then(), just use 'component.setState'   // instead of 'this.setState'    // Simulate async   setTimeout(() => {     component.setState({       name:,       currencies: "whatever",       languages: "yep"     });   }, 1000); };  export default getSettings; 

It's as simple as that.



:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: