How to refresh a component from another component in Salesforce LWC? - salesforce

In Salesforce LWC (Lightning Web Component) -
I have created two different components i.e. ComponentA, which is use for create a new record and ComponentB which is displaying list of added records. Once user clicked submit button from ComponentA then ComponentB should be refresh/reload.
Can anyone please help?

If the components are related (if one contains the other) you can use events to communicate the child component with the parent component by using the dispatchEvent() method (https://developer.salesforce.com/docs/component-library/documentation/en/lwc/lwc.events_create_dispatch).
If the components are not related, then you can use the a Message Channel to stablish a communication between them. You would need to:
Create the Message Channel => https://developer.salesforce.com/docs/component-library/documentation/en/lwc/lwc.use_message_channel_intro
In ComponentB (the receiver) subscribe to the channel => https://developer.salesforce.com/docs/component-library/documentation/en/lwc/lwc.use_message_channel_subscribe
In ComponentA (the emitter) publish a message to the channel that the ComponentB will receive => https://developer.salesforce.com/docs/component-library/documentation/en/lwc/lwc.use_message_channel_publish
Hope this is useful.

Related

how to handle subcomponent completion eventsin react / flux / redux

I am designing an application in react/redux and I am new to flux/redux and unidirectional patterns. I ran into a problem which I am not sure how to properly solve within a unidirectional architecture
I want to illustrate the problem with the example of a user registration form that might show up in different parts of the app. Please note that the core problem is about if and where to handle subcomponent completion events and the UserRegistration is just an example.
Let's say I have a component UserRegistration which will render as a form. This component will handle its own submit action which may include some asynchronous calls to a server endpoint and in the end should lead to a modification of the store/state (e.g. adding new user data).
The user flow is the following:
user clicks on 'register' button
user sees registration form
user types in data and clicks 'submit'
user registration form disappears
I want to include this UserRegistration form in different places in the app.
Let's say I want to show the registration form based on a route /register and after succesfully registering I want to route back to /.
The intuitive thing for me to do (coming from a non-unidirectional world) would look something like this
function MyApp() {
const isRegisterRoute = //... somehow check if /register is active
return (
<button onClick={ () => { routeTo('/register') }}>register</button>
{
isRegisterRoute && (
<UserRegistration // handles actual registration internally (network calls and store modification)
onCompletion={ () => { routeTo('/' } } // pass completion handler which will route back to initial path
/>
)
}
)
}
This would solve the problem but I am wondering if having a callback for such a component with a complex flow is an anti pattern in a unidirectional architecture.
One concern is that the callback basically inverts the direction and it's no longer unidirectional.
Another concern is that I would have to pass the onCompletion handler down the chain within my component so it gets executed once the registration is complete. This passing around of the handler does not feel clean as it leaks into a lot of places.
On the other hand I don't want to handle the routing back to '/' inside the UserRegistration component as the success route or action might be different depending on where I use it so I want that logic to be decoupled from the component.
What would be the appropriate/best-practice solution for the problem described above within flux?
It's not data flow at all
It's not an anti-pattern as I don't see any data flow from sub-component to parent, like
<SubComponent onComplete={data=>this.setState({data})}/> // not good
reroute to another router is logic, the next router is the property passed to UserRegistration component, so it's the same as
<UserRegistration nextRouteOnComplete="/"/> // property
and handle routeTo logic in UserRegistration.
A function can be dynamic, do make sure no data will be passed to the callback function, the callback is designed to handle logics after complete, no data should be passed, and data update should follow the unidirectional data flow,
dispatch action -> reduce action -> mutate state -> rerender

React - How to connect / disconnect children components to data from parent based on click?

Parent component provides data to child component (that displays it) (have multiple children). The child component has 2 buttons connect and disconnect. When connected to should receive and show the data, when disconnected clicked, it should disconnect from data.
How I would do it: child calls method in parent for connect/disconnect,then i would have a flag in parent state and based on that either render child with or without data, then inside child i render props or null if no props provided.
That would mean if I have 10 child components, I would need 10 flags which doesnt seem good, so I 2nd idea:
having the flag insight the child and method for triggering connect/disconnect, render based on if props were provided
My question is, is there a good practice react way of connecting children to parents data flow/stopping data flow without always passing data to children and just rendering/not rendering it based on if child 'wans' to be conencted or not?
Thanks!
Did you try using Redux or Context API?
The two are very similar and it should get what you want.
They basically use 1 store(think of them multiple states are connected to 1 store) and you get data from child components.
After getting your data you can check if user is logged in or not and put your buttons according to this data.
If I was not clear enough feel free to ask any question.
Also official docs for Redux and Context API are:
https://redux.js.org/introduction/getting-started
https://tr.reactjs.org/docs/context.html

Control component states from App.js and change their values

I have an IOT application that communicates with ble devices. So I use react-native-ble-manager.
In this package, you have to use event listeners such as;
bleManagerEmitter.addListener( 'BleManagerDidUpdateValueForCharacteristic', this.handlerCharListenerSettings);
(For more information you can check this)
So I use these event listeners in different screens, but it's not a proper way. Because In every screen that has event listener loads this addListener and this causes problems. In componentWillUnmount event you can clear these listeners, but the correct way is to control all these listeners on one logical place such as App.js or anywhere similar.
My problem begins here:
I have different screens, I want to set their states from App.js. I mean when I change a value from App.js event listener, I want to make the other screens affected by this value. How I can do this or is this a proper way of using listeners?
My RN version is 0.58
If you want to share the listener either use the Context API as mentioned or create a wrapping component. Much like the App.js create a new component:
<Wrapper>
<YourApp/>
<Wrapper/>
class Wrapper extends React.Component {
componentWillMount() {
bleManagerEmitter.addListener( 'BleManagerDidUpdateValueForCharacteristic', this.handlerCharListenerSettings);
}
}

why do we need container component in react-redux

I understand why we want to extract data logic from component into somewhere else, but why do we have to put this logic in a container component, rather than a controller-like javascript object which is connected to the component. This object will subscribe to the store and force the view to update itself when data changes. This way it does not has to be part of view structure and only handle data.
Thanks for help.
In Redux, connect replaces the need to use an explicit separate container component. So, essentially, you're completely right, you don't need to literally create another component that just renders the dumb component.
I create a dumb component and then I have a separate file where I connect the component, but there's no JSX or separate component in this file.
const DumbComponent = (props) => <div>{props.name}</div>;
const ContainerComponent = connect(mapStateToProps)(DumbComponent);

State of child components in React

Should child components never have a state in React? I understand that state should be maintained by the "wrapper container" or parent container and it should have unidirectional flow. I have started with React and have a header container with upto 10 child components.
Let's say one of the child component is a Form with a submit button that can be enabled or disabled.
Should this child component not be able to have a constructor with state initialized for the button and be able to directly manipulate it or is it important that I maintain states as minute as this in the wrapper container "only"?
You should let the parent container manage the state of forms. I usually attach an onChange listener to each input and then when the submit button is clicked I call a function in the parent component to submit the value contained in the state for my form inputs. The form should only render inputs and do nothing else, basically a dumb component.
The purpose of React is providing a component system to front-end. It does not specify/enforce how state flow. People generally prefer state-less components because it is easier to share and distribute. However, front-end component can never be fully state-less + declarative.
In my opinion, you should feel free to use this.state to manage local state when you feel appropriate.

Resources