ReactJS Passing Data Between Components (search bar) - javascript

Hello everyone Im doing a search bar using react and got a program, before I was passing data between components parent > child, child > parent but now I need to pass from my src>components>toolbar>search bar to src>containers>category component, someone could help me?? thankss

Another way to achieve this, by creating and dispatching an event and listing this in a component.
componentDidMount() {
this.nv.addEventListener("custom-event", this.handleNvEnter);
}
componentWillUnmount() {
this.nv.removeEventListener("custom-event", this.handleNvEnter);
}
handleNvEnter = (event) => {
console.log("custom-event:", event);
}

I looked at your question and the first thought that came to my mind was introducing Redux.
You can do this by installing a few packages using npm.
Redux (core library for Redux) Redux documentation
React-Redux (Redux is a apart from React and needs this package to work cohesively) React usage with Redux
Honestly I could ramble on and tell you how to integrate every little detail. But I'm not going to do that instead I'll give you an overview of how you would use this technology to your benefit. Be warned this is going to require a bit of time to master, however in doing this your ability to design complex systems will be greatly enhanced.
Firstly, you're going to want to learn a bit more about how Redux stores and data. Here is an introductory course by Dan Abramov the creator of Redux Redux course. It isn't too long and is free!
Once you're familiar with stores, reducers, action creators, actions and the Provider component --->Close your laptop<--- and take out a pen and paper and map the hell out of what belongs where. For instance, your search data belongs in a reducer that handles it, and your going to have to design your actions accordingly too plus read their payloads and map them to the store.
Now code it. With the design being completed and necessary information on how to develop with redux, this should be a stroll in the park.
Hope this helps your question.

I think the best way to solve that problem is to use Redux (https://redux.js.org/basics/usagewithreact) which is typically used for storing the values and which you can use it throughout the application files.
The below links will help you understand Redux and how to implement to your react application:
https://github.com/bradtraversy/redux_crash_course
https://www.youtube.com/watch?v=93p3LxR9xfM&t=537s
https://github.com/bradeac/using-redux-with-react/tree/master/src

You can pass the data up to the topmost parent and then pass it down again to the child you want to.

Related

What is the best way to manage your actions in Redux?

So I have heard it's good to keep them all in one folder in your src folder but then if I ever wanted to use the action from somewhere deep in my component tree, I'd have to:
import increment from '../../../../../actions/increment';
Alternatively each action could be kept in the folder I'm using it in, but then if two different components needed to use the action, I'd have to send the action through props or make a copy of it.
I'm sorry I'm a complete newbie with Redux. Is there a nice concise way to do this?
If you follow current standards, you don't even write action types or action creators. Please read Why Redux Toolkit is How To Use Redux Today.
As for the question as hand, file organization is handled in the Redux Style Guide

When should I use Redux in my react application?

I'm working on a react web app and our company bought an admin dashboard panel to save time. In this panel, they used redux to handle states and all setting parameters stored into redux ...
But really I'm confused about using Redux for each use case!
All of my requests and states are components base and are not global and those are not essential to use in other components of this app!
For example to load games list I've this code :
componentDidMount() {
this.setState({
loading: true
});
http._GET('/game/getAllGames')
.then(response => {
this.setState({
loading: false
});
this.props.dispatch(gamesListAction(response.data.result.games));
});
}
In this case, I use a response and list only on the games-list page. So I think it's not logical I store a response.data into redux and then get all data with connecting and another process...
Or another example, for inserting forms I'll never need to store forms insert or API response because it's inserted and not getting data from API!
I've read about redux but I think redux is not suitable for every app and use case and I should not store single-use responses to redux.
The reduxjs FAQ describes it the best.
In general, use Redux when you have reasonable amounts of data changing over time, you need a single source of truth, and you find that approaches like keeping everything in a top-level React component's state are no longer sufficient.
Redux is nothing but a state mangement tool and you need more compelling reasons to use it:
In your case, firstly:
React's setState will bloat the component overtime with growing requirements and it is much
harder to maintain. Separating out the state management into a reducer
refactors nicely and makes it more readable.
Caching component state, for example if you are using a shopping cart, progressive wizards. There a is lot of to and fro in user interaction which result in state changes, in such cases. Maintaining your state in redux makes a lot of sense now.
Deeply nested components passing on state and lots of props to their children quickly bloat with growing requirements. This is a classic scenario with lot of wrapper components (especially with UI details). A better way would be to refactor and directly connect low level components to redux (transform into a container. Read: presentational-and-container-components)
Application state mapping to multiple container components. For example, if you had your getAllGames loading state to be represented in some progressive-loader-component somewhere out in your app. Using redux will ease your pain sharing data between this components.
Useful when building root level components which can possibly have interactions from everywhere. Like your useraccount component, modal, alerts, loaders.
You will realize, you are writing some boilerplate code with actions and reducers. Though overtime this is much better than reacts state management which can progressively grow complex within stateful components quickly.
Yes, You are right redux is not suitable for every application, as per my knowledge redux or state management is used mainly if you want to show the user previous state instead of empty when some operation is happening
Here is a bit detailed explanation about when to use redux
https://medium.com/#fastphrase/when-to-use-redux-f0aa70b5b1e2
Happy Coding !

How & when to best modularise Components with & without Redux?

Say I want to create a little editor for my software that helps me organise people in my company. I will use React & Redux. The editor is a React component (or maybe container?), and it shows me one person at a time. I can edit things about this person, delete fields, etc. and when I am ready I can click a button which will then give me the next person to edit.
Now, I am quite new to React still and can imagine doing this in 2 ways:
Solution 1: Decouple the editor component
Create an Editor Component, which takes an array of all the people in my company. I do have these people saved in the Redux state of my app, but the editor component will not work on my Redux state, but do all changes in its internal state first, and only once I click save will the Editor component commit these changes to my Redux state. This might be a problem, and changes could get lost if somebody doesn't save their edits.
The advantage here is that I have my Editor de-coupled from the rest of my App, and the logic of the Editor will stay in that component.
Solution 2: Connect the Editor Component to Redux
Here, I would connect my Editor component to Redux. So I would not give my component the people array, but direct access to the my Redux store via selectors (for example). I would also not have a deletePerson() function internal to my component, but pass this down as a prop into my component (and it would presumably be a Redux action). This way my component would work directly on state, which I can see as having advantages.
But taking it out of this app and reusing it somewhere else would get more and more difficult, the more complex my component becomes.
Please remember that I am a beginner and that these two solutions are what I came up with as a response to a problem I am facing in my own application. However, I would appreciate if you could help me out here, and explain to me how I should think about problems like this. Is there maybe a third solution I am not mentioning? Or am I misunderstanding a concept?
Personally, I am inclined to go with Solution No. 1, but I also know that the whole idea of Redux is to keep state in one place. What would you advise? Are there performance differences / advantages with one solution?
Your first solution is good but why not use a service when its provided?
You should try to mix up features of Redux React. First, separate your presentational and container components and in one of your container component pass the props directly to redux store on click,etc. Then use redux actions to access the store like deleting,etc. Provide a UI using React presentational components for data entry and pass this data to redux store. Use redux actions when you think they will be useful and not destructure your app.
Go to https://medium.com/#dan_abramov/smart-and-dumb-components-7ca2f9a7c7d0 for further details on how to connect presentational and container components.

Redux Alternative [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 2 years ago.
Improve this question
I have recently started learning React and I quickly encountered the problem of a bloated parent component full of functions and state. At first I looked at Flux and then I looked at Redux but both seemed like really overbearing solutions.
I am wondering why something like this is not done:
//EventPropagator.js
let EventPropagator = {
registerListener(listenerObject){
if (this.listeners == null)
this.listeners = []
this.listeners.push(listenerObject)
},
fireEvent(eventObject){
let listenerList = this.listeners.filter(function(listener){
return listener.eventType === eventObject.eventType
})
listenerList.forEach((listener) => {
listener.callback(eventObject.payload)
})
}
}
export default EventPropagator
To use: components simply registerListener and fireEvent:
//main.js
import EventPropagator from './events/EventPropagator'
EventPropagator.registerListener({
"eventType": "carry_coconut",
"callback": (payload) => {
// actually carry coconut
this.setState({"swallow_type": payload.swallow})
console.log(payload)
}
})
EventPropagator.fireEvent({
"eventType": "carry_coconut",
"payload": { "swallow": "african" }
})
This would allow a lot of decoupling and state could easily be passed around with this sort of event. What are the downsides to this approach?
You should try mobX
mobX is a state management library which took the advantage of decorators and succeeded in removing unwanted code. For example, there is no concept of reducers in mobx.
Hope this helps!
There is Reactn based in hooks.
It is orders of magnitude easier to use, compared to Redux.
Check https://www.npmjs.com/package/reactn and read Stover's blog.
Redux is a continuation of React's declarative programming Style. A simple way of mapping your application logic to components is to use something like Backbone.React.Component but using redux, will let you use all the tooling & middle-ware. Also have indefinite transitions in your apps makes debugging a lot easier. Now, I agree that you need a lot of wiring & boilerplate to get anyway.
If you want to use redux, you could look at something like redux-auto
Redux-auto: Redux made easy (with a plug and play approach)
Removing the boilerplate code in setting up a store & actions. why? This utility to allow you to get up and running with Rudux in a fraction of the time!
You can see now a redux-auto: helloworld project
If you want to take advantage of all the Redux benefits, use Redux.
If you only want to keep a var on sync between React components, use Duix.
I'm the Duix's creator. I've been using it for 1 year, and finally, I released it a few hours ago. Check the doc: https://www.npmjs.com/package/duix
You should try Hookstate. It gives the same simplest API for local, lifted, and global states. First class typescript. DevTools support. Extendable with plugins. Comprehensive documentation. It has got state usage tracking feature and smart re-rendering of only deeply nested affected components. This makes it the fastest state management solution for large frequently changing states. Disclaimer: I am maintainer of the project.
What is needed is an event driven system so a child component can speak to its sibling but this does not mean that data should be passed as the events payload. That would lead to a system of no governance and a nightmare for a project where multiple developers are working on it.
So long as you follow the flux-like architecture pattern (google it) then you actually can do this successfully with just javascript and Javascript objects to hold the data along with the event system.
Data should be treated as being one of three different states. It's either
original data pulled from the server
transformed data (transformed from the original)
Store data. That which acts as the model which the UI is bound to
If you write a javascript library to handle the movement of data between the three states and handle the transforms you can use the event system to to fire a "store changed" event that components can listen to and self-rerender.
https://github.com/deepakpatil84/pure-data
Note: i am the author of this
Using your EventPropagator solves the problem of communication, but does not handle data integrity. For example, if there are more than 2 components listening to same event, and using that event's payload to update their own states. The more components listen to same events, the more complex it is to make sure that all those components have same data in their own states.
Secondly, Flux/Redux provides uni-directional data flow. A simple example could be about 2 components A & B, consuming same data X from external source (API or storage). User can interact with either of them to get latest X data. Now if user asks B to update X, we have 2 solutions with your EventPropagator:
B will update X itself, and fire an event to inform A about the update to let A re-rendered. Same goes for A if user asks A to update X. This is bi-directional data flow.
B will fire an event to A asking to update X, and await A to fire an event back to get updated X. If user asks A to update, A will do it itself and inform B. This is uni-directional data flow.
Once your number of components goes large and communication is not limited between only A & B, you might need to stick with only one of those 2 above solution to avoid your app's logic going wild. Flux/Redux chooses the second, and we are happy with that.
If you really don't think you need another library for data control, you should look at the newest feature of React: Context. It provides most essential features that a data control library can have, and it's React only. Noted that you have to update your project's React version to 16.3 to use this feature.
Another modest multi-store alternative is react-scopes
Here are some features:
Simple decorators syntax,
Allow defining independent store logic directly in Components
Easily connect stores through the Components tree
Allow templating complex / async data process
SSR with async data
etc
I wrote Reducs. It's only 25 lines of code, it doesn't require boilerplate, and... did I mention that it's only 25 lines of code?
I am using it for a big project, and it's holding up very well. There is a live example that uses lit-html and Reducs.
I faced similar issues, with lot of switch, case, etc...
I create for myself something as alternative, you could take a look:
https://www.npmjs.com/package/micro-reducers
Take a look on JetState for state management with RxJS. I wrote this for my Angular projects and later adapted it for using with React's hooks.
PullState I really want this underdog to shine. Tried other similar ones which promised quick and no-boilerplate-ness, none came close to the ease of use of PullState. I just read the first page of the documentation and implemented it in one of my pages and it just worked. It is easy to understand if you already using functional components in react.

tring to reduce the redux boilerplate with some utils

I was wondering if there's something wrong with the approach I'm trying in this link:
https://t.co/WSV81eDwkr
Basically the idea is to modify only the actions file when you add a new action.
on of the Improvement I'm thinking is to recursivle merge the status passed from the actions with the reducer's state.
Let me know
Good thinking. Unfortunately this is an anti-pattern in redux. Actions are supposed to be "pure", stateless, and non-mutating. You are accessing the state directly from an action, which is circumventing the flow of data (oldState => view => action => reducer => newState). Of course the framework is there to help you so if you find that this solution scales well with your project, it could be the way to go.
But to answer your question, it's definitely the wrong approach if you are trying to keep the Redux approach. Another issue I see is that you can't easily serialize actions so it'll likely break time traveling and the redux dev tools if you were to use them.
It's true that there's quite a bit of boilerplate involved in Redux but it's the price to pay to overcome all those CONS you listed with this new approach. Debugging the state of your application is much harder in this scenario.

Categories