Strahinja Ajvaz
Strahinja Ajvaz

Reputation: 2643

passing value to child without saving it to state

I have an app that im working on and im stuck on one part. I have a component that i use to fetch data from a server which then I need to pass into another component.

Since this could potentially be a big payload, i don't want to use a global variable to store the data and then pass it when render gets called nor do i want to save the data to the state, as the data has nothing to do with the App component.

Is there a way in which i can pass the value that i receive from componentDidMount() to the render function and pass it as props to the desired component?

Thanks in advance!

*edit:

// code
componentDidMount() {
    // gets the data
}

redner() {
    return <Node value={*Needs to be passed here*} />
}

This snippet is all in my app component. I need to pass the data from componentDidMount() to render without using state or global variables.

Upvotes: 0

Views: 70

Answers (1)

luboskrnac
luboskrnac

Reputation: 24571

render function is called every time component props are updated. Unless you explicitly disable it in shouldComponentUpdate. So you should get all the props changes in render function (if you are updating props correctly).

EDIT:

After updating answer I hope I understand the problem correctly.

In your case the best way is to use state to share data between async promise/callback and render method. Setting up state via this.setState method ensures that component is re-rendered.

Something like:

// code
componentDidMount() {
    // gets the data
    this.state = {}; init state
    axios.get("/data")
        .then(response => this.setState({ data: response.data }));
}

redner() {
    return <Node value={this.state.data} />
}

Upvotes: 1

Related Questions