I have react hooks section in which user can edit input fields, there are hundreds of inputs that is why I need to use redux (newbie to redux though),
Live demo on codesandbox: demo
so far I have this
const initialState = { firstName: "Kunta ", lastName: "Kinte" }; const detailsReducer = (state = initialState, action) => { const { name, value } = action; return { ...state, [name]: value }; }; export default detailsReducer;
and here is setting js where I have input fields
import React, { useState } from "react"; import { useSelector } from "react-redux"; import Details from "./Details"; import DetailsReducer from "../Reducer/DetailsReducer"; const Settings = () => { const fields = useSelector((state) => state.DetailsReducer); const [state, setState] = useState(""); return ( <div> <div> <h1>Edit </h1> <div className="container"> <div className="inputs"> <label htmlfor="fname">First name:</label> <input type="text" id="fname" name="fname" value={state} onChange={(e) => setState(e.target.value)} /> <label htmlfor="lname" /> Last name: <input type="text" id="lname" name="lname" onChange={(e) => setState(e.target.value)} /> </div> <Details /> </div> </div> </div> ); }; export default Settings;
Expected results: Just when the user types in inputs eg first name it should change the value of the first name in the details component.
I am strugling to get this working can some please help?
Advertisement
Answer
I forked your CodeSandbox and got a working example here
Some notes on what I did to get it working.
- Added
redux
package which is the core redux functionality. This is what lets you create a redux store. Check out the docs here. - Create
store
with theDetailsReducer
usingcreateStore
fromredux
package. View this here. - Wrapped
App.js
with theProvider
fromreact-redux
. This is where you pass your reduxstore
. Check docs here. This is important as it is the integration that allows react applications to work with redux. Without this, you can not useuseSelector
oruseDispatch
for example. - The next part is using the redux state values and dispatch on the input fields which you can see here.
Just to be clear, the redux
package is the core redux functionality. It is designed this way so redux can be used anywhere (like server side with NodeJS). The react-redux
package is the react integration that makes consuming redux easy for react applications.
Side Note: Technically when you call dispatch you pass a type
and the type controls how the reducer changes its state. Your example is so simple, there is no need for a type which is why in the example you see the type as an empty string. Here is an example of using the type
though in the docs.