-2

I am still a rookie in frontend. I have 2 NON RELATED (no parent/child relation) classes:

search.js
Class Search{
   method,
   state
}

view.js
Class view{
     content
}

I am trying to:

  • call a search.js method from view.js.
  • change state value of search.js from view.js

Additional info:

  • I have already tried using helper functions. It was not the desired solution.
  • I am using Preact which is a leightweight version of React.

Thanks!

Code:

export default class Search extends Component {
    constructor() {
        this.state = {
            input: ""
        };
    }

    search(input) {
        this.setState({ input: input });
    }
}
Foo
  • 596
  • 2
  • 5
  • 21

3 Answers3

3

If the classes are unrelated, then there are only three ways you can use a class's methods outside the class (or, really, inside it):

  1. If it's a static method, call it directly:

    Search.theStaticMethod()
    
  2. If it's a prototype or instance method, the usual thing is to create an instance and then call the method on that instance:

    const s = new Search(/*...*/);
    s.prototypeOrInstanceMethod();
    
  3. If it's a prototype method, you can call it without creating an instance, but it's extremely likely to be incorrect to do so:

    // ALMOST CERTAINLY NOT THE RIGHT THING
    Search.prototype.prototypeMethod();
    

    There's a variation on that where you apply the method to an object, even though that object wasn't created via new Search:

    // ALMOST CERTAINLY NOT THE RIGHT THING
    const obj = {};
    Search.prototype.prototypeMethod.call(obj);
    

    The method will get the object as this, and may or may not work correctly depending on how it's written.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
1

You need an instance of class as answered already.

const myInstance = new Search();

You can export this instance instead of exporting class.

export {myInstance};

In view.js you need to import it

import {myInstance} from './relative-path';

And then you call method

myInstance.search('someInput');
Alonad
  • 1,986
  • 19
  • 17
1

Taking more react than vanilla js ... probably already answered here or even (primitively) here

I have 2 NON RELATED (no parent/child relation) classes:

Both in the same screen/view/app/component tree? Then indirectly but still related.

I am trying to:

  • call a search.js method from view.js.
  • change state value of search.js from view.js

There are a few ways to manage common state (values or methods):

  • state in common parent ( lifting state up ), even top <App /> component
  • using refs
  • using context api
  • redux
  • apollo client

Using Preact - then search for some tiny global state management, f.e. statext or unstated

xadm
  • 8,219
  • 3
  • 14
  • 25