Does React need Flux for one way data flow? - reactjs

I am very new to react. Whether one way data flow in react is achieved only through flux(action and store) ?.
<div id="container"></div>
var Hello = React.createClass({
changeState: function (event) {
this.setState({
sampleState: event.target.value
});
},
getInitialState: function () {
return {
'sampleState': 'World'
};
},
render: function () {
return ( < div > Hello { this.state.sampleState}
< input onChange ={ this.changeState}> < /input>
</div >);
}
});
ReactDOM.render( < Hello / > ,
document.getElementById('container'));
I have changed the state of a component without flux.Does this fall into one way data flow ?

The idea of React's one way data flow is that data goes down the application.
A
/ \
v v
B D
| |
v v
C E
Component A can pass data to Component B, which can pass to C. Simlarly, A can pass to D which can pass to E.
Parents components can pass data to their children and so on down the component tree.
Child components can't pass data back up to their parents.
Your example doesn't have a directional data flow, because you're only working with one component. The data isn't moving when you change state — it's encapsulated within the component.
A
If you added another component to your example and passed properties down to it, you would introduce a one-way, downwards data flow.
A
|
v
B
The Flux architecture allows you to create cycles in your flow. Data goes down the tree, then out to Flux in the form of an action. This action updates a store, which in turn updates the components that are subscribed to that store.
A <- [store]
| ^
v |
B -> [action]
This keeps the data flowing in a single direction. Any component can subscribe to a Flux store, but if that component wants to make meaningful change to a component that is higher than itself in the tree (for instance if B wants to change A), it must go round in one of these cycles, rather than simply flowing back up the tree.

Related

Store in XSTATE for accessing across components?

I have component A and component B where in after some selection in Component A, Component B should be able to get update state or selection.
I have allocated separated machines for MachineA and MachineB respectively.
I want to know how to get the context of MachineB in Component B which gets updated in Component A.
For eg.: Component A fetches data from Machine A and updates context of Machine B with selected product.
Now Component B should be able to access store of Machine B which is updated. Any idea how to do this? I do not want to pass state as props.
Lift the state up, and use context. Put both machines in the context, so all the components share the same instances of the machines.
You should provide some code, you are using reactjs and angular tags so is hard to know what you have con your code.
Anyways, I'm not sure if you are already invoking the B machine inside the A machine, thats the first step to connect them.
The second step is using the B machine on component B but from the A machine.
On react will be something like this
// A machine file
const AMachine = Machine({
id: "aState",
initial: "initialState",
invoke: [
{ id: "bState", src: BMachine }
],
states: {...},
}
// A component
const [state, send] = useMachine(AMachine);
const AMachineContext = React.createContext(null);
<AMachineContext.Provider value={state}>
<BComponent />
</AMachineContext.Provider>
// B component
const aMachine = useContext(AMachineContext);
const [bState] = useService(aMachine.children.bState);

Updating state based on selection (Redux)

being new to redux, I came across the following challenge: I have a filter-list, which must be updated both after the first load of a component, and every time someone changes a dropdown in the top navbar. The filter-list is dependent on another dropdown which is part of my state. A pseudocode is below [1].
I could theoretically duplicate my action dispatch in both Components (the main one and the navbar), but this is bad design of course.
This brings me to the question: Where does one put redux dispatch calls which must access the state themselves? Would this live in the action-file which would then need to access the state itself (which might not be good design on its own)?
Thanks!
[1]
function getDrillOptions() {
let data = props.data; // <- is part of redux' store
let countries = props.selectedFilters.countries; //<- part of redux' store
let regions = getRegionForCountry(countries);
let selectable = new Set();
Object.keys(data[regions][countries]).map((weeknum) => {
data[regions][countries][weeknum].map((row) => {
selectable.add(row[event.target.value]);
});
});
dispatch(populateFilters({filter: 'mainDrillOptions', value: [...selectable]})); // <- sets state
}

How to pass props from unrelated component

I need to plot a table using data from header component ( 2 drop-downs & one Apply button), while header, table section & footer are unrelated to each other
I have tried to create an array in separate Utils file, which is populated when Apply button is hit, it is passed as
<Table data={utils.sortArray}/>
While data is populating sortArray when Apply button is hit in header component, it is showing length 0 Still
When Apply button is hit, new array data should get passed to table component
If you need the table to update based on input in the header the components aren't really unrelated (they are related through the data they have in common / are sharing).
To communicate between the two you will need a way to pass the data - the logical approach is to have the parent component coordinate between the two as it is contextually aware of both. In this case, you can:
Pass callback a prop to your header component that you call with the required data
Store the data sent in the callback in the parent's state
Pass the state data to your Table.
E.g., in your parent component:
state = {
sortArray: '', // What ever your default value is
}
onSort = (sortArray) => {
this.setState({
sortArray,
});
}
render() {
...
<Header onSort={this.onSort} />
...
<Table sortArray={this.state.sortArray} />
...
}
And then call onSort in your header with the required value as needed.

React - comunication between components (for beginners)

I am realatively new in React JS. Few weeks ago I created To Do List app in JS, jQuery and now I am going to rebuilt it using React, just for change my point of view and practice React.
I have few components (siblings) in different files and one parent component - App, components:
App:
- Navigation
- Task List
- Add Task
- Footer
How can my navigation component communicate with task list component?
To be more specific I want to have something like global variable selectedDay and use it in all components.
When user choose in Navigation component single day, for example Sunday , I want to save "sunday" in this variable and later use it in Task List (this is of course sample example of data). My question is how to store data in first component and use it in another one?
Should I use state for this kind of purposes? I was thinking about set initial state in parent (App) component -> selectedDay : "monday" /default/ and later update it by Navigation component and use in Task List component. Could you help me, please? I will be gratefull!
There are two solutions for this.
1- Use a library that handles a global state, like Redux (as FurkanO said). That way, your "big components" (aka containers) are connected to the global state of your application, and update it with actions.
Actions are some kind of events with a type, and sometimes a payload, that will be intercepted by a reducer and trigger a state update.
2- Use the state of the lowest common parent of the components you want to see interracting.
Basic Example for 2- : Parent Component contains Navigation & TaskList.
class Parent extends Component {
state = {
selectedDay: defaultDay,
}
setDay = (selectedDay) => {
this.setState({ selectedDay });
}
render () {
const { selectedDay } = this.state;
return (
<div>
<Navigation setDay={this.setDay} />
<TaskList selectedDay={selectedDay} />
</div>
);
}
}
Then you just use this setDay function in your Navigation component to set the state in the Parent Component. That way, your TaskList will receive the new value via its props.
This method has its limits (it really doesn't scale well in my opinion).
Hope that helped. Please tell me if this isn't clear for you.
What you need is redux. It provides you a global state tree which is an object, a way to manipulate it and most importantly whenever your state tree changes rerenders your components. So that your components are always up-to-date with updated state tree.

using valueLink, child input field unable to change

I'm starting to play with reactjs, and for this project, I have ->
an input field
a button that toggles a modal
the modal has another input field.
How do we make both input fields stay in sync?
What I though I would need to do use to use the LinkedState mixin.
So, I do something like this ->
MainFoo = React.createClass
mixins: [React.addons.LinkedStateMixin]
getInitialState: ->
searchTerm: ''
render: ->
input valueLink: #linkState('searchTerm') # this works
CustomReactChild
searchTermLink: #linkState('searchTerm') #passing into child.
CustomReactChild = React.createClass
renderModal:
unless #modal
$anchor = $('<div>').appendTo('body');
comp = (Modal
body: (CustomReactChildchild
searchTermLink: #props.searchTermLink)
) #custom react modal class
#modal = React.renderComponent comp, anchor
#modal.show()
render: ->
label
onClick: #renderModal
# Deep inside CustomReactChild
CustomReactChildsChild = React.createClass
render: ->
input valueLink: #props.searchTermLink # Am unable to change the value via this input
Am I using this incorrectly? How can I get the second input to change the value of the parent's input and vice versa?
#Douglas popped in an awesome answer in the comments -->
Looking at the logs here, jsfiddle.net/kb3gN/3602 - I think part of the problem is that the modal popup is re-rendering (or at least running the "Controlled Input" handler) before MainFoo has updated its state. I'd suggest merging the models together, so that there is only one React.renderComponent call, or factor out the state into a shared Store which both inputs update and get change events from.
```

Resources