Reputation: 1883
I have a component called Info
in this path:
compontent\Agent\Info
And get data
from axios
in componentDidMount
:
async componentDidMount() {
let data = await API.getData();
this.setState({
result: data.success
});
}
I add data
to state.result
and got this.state.result.unread_message
here, now I want to pass this.state.result.unread_message
to another compontent called SideBar
, to avoid double request. Like this:
template\SideBar
Code:
<Label>{this.props.unread_message}</Label>
These are not child or parent, how can I pass data
from axios in one component to another component?
I tried and followed this answer but it not worked as expected and also render whole sidebar in info!
Upvotes: 1
Views: 94
Reputation: 13892
There are a lot of answers to this question, some more complicated, some more standards-based, some which people would say 'never do this'.
One option: inside your Sidebar component, create a global function, window.onDataUpdate = (result) => { this.setState({result}) }
, just as an example. And then, when you get the updated data anywhere else, you can call window.onDataUpdate(result)
. A lot of people will think this answer is unacceptable because it uses a global function. Depending on the size and complexity of your project, perhaps that's true, this wouldn't be the right approach. If it's a real simple little project, I'd probably give it a pass though.
Another option is to have an object, stored in another file, that you can import into both files, that allows you to register listeners and trigger updates. So when your Info component gets the updated result, it can call the 'trigger' function on that other object, which in turn calls all registered callback listeners.
Or even use a normal default Javascript event that gets triggered with updated data. following the guide here
A common answer in React world for this type of scenario is to store the state with Redux as well. That may be over-complicated, especially if this is the only thing you'd be using redux for.
Upvotes: 1
Reputation: 1311
You can use react's context API's
for that. Read more about it here.
Upvotes: 2