0

i need to know how to fetch state of component from other component by calling the seconed component method inside of first component ? like :

class General extends Component {
    
  state = {
    input:"
   }
   
   fetchState() {
    return this.state;
   }

  handleChange () {
    this.setState({[e.target.name]: e.traget.value});
  }
  
  render() {
    return <input type="text" name="input" onChange={this.handleChange.bind(this}>
  }
  
}


class Car extends Component {
   
  render() {
    console.log( General.fetchState() );
    return null;
  }
  
}

i know i can use static method but i don't have access to this keyword.

4 Answers 4

1

The recommended way of doing that kind of things is by composing components and passing the parent's states as props

class General extends Component {
  state = { ... }

  render () {
    return (
      <Car {...this.state} />
    )
  }
}

class Car extends Component {
  render () {
    console.log(this.props)
    return (...)
  }
}

Now if you want to share a global state between components could be a good idea to use context api with hooks.

import React, { createContext, useContext } from "react";
import ReactDom from "react-dom";

const initialState = { sharedValue: "Simple is better" };
const StateContext = createContext({});

const General = () => {
  const globalState = useContext(StateContext);
  return <h1>General: {globalState.sharedValue}</h1>;
};

const Car = () => {
  const globalState = useContext(StateContext);
  return <h1>Car: {globalState.sharedValue}</h1>;
};

const App = () => {
  return (
    <StateContext.Provider value={initialState}>
      <General />
      <Car />
    </StateContext.Provider>
  );
};

ReactDom.render(
  <App />,
  document.getElementById("root")
);

Here is the example link.

And here I have a repo with a more elaborated example managing global state with just hooks.

Sign up to request clarification or add additional context in comments.

Comments

1

There are many approaches, I suggest using a general state accessible from both components.

Check ReactN for simplicity or Redux for a more robust solution. Note Redux has a big learning curve and quite some boilerplate that, depending on the size of your App, it could not be necessary.

Using globals is not advisable on many situations, but to answer your question, you could also do this:

General component:

class General extends Component {
    constructor(){
        global.fetchGeneralState = this.fetchState;
    }
    fetchState = () => {
        return this.state;
    }
}

Then from the Car component, you can just call: global.fetchGeneralState(); and you will get the state from the General component.

Comments

0

In your current code, the only way to do it is to use new General.

console.log(new General().fetchState());

1 Comment

By doing new General() the "original" state is going to be lost.
0

If you expect to use Car component as a parent of General component, then you can simply use ref. Here is the modified code of yours that I have tested :

import React from "react";

class General extends React.Component { 
    constructor () {
        super();   
        this.state = {input: ""}
        this.handleChange = this.handleChange.bind(this);
    }   

    fetchState() {
        return this.state;
    }

    handleChange(e) {
        this.setState({[e.target.name]: e.target.value});
    }

    render() {
        return <input type="text" name="input" onChange={this.handleChange} />
    }
}

export default class Car extends React.Component {   
    constructor () {
        super();
        this.refToGeneral = React.createRef()
        this.handleClick = this.handleClick.bind(this)
    }

    handleClick() {
        console.log(this.refToGeneral.current.fetchState())
    }

    render() {
        return ( 
            <>
               <General ref={this.refToGeneral} />
               <button type="button" onClick={this.handleClick}>Show State</button>
            </>
        )
    }  
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.