I'm learning redux. This is a simple project for understanding react redux. The basic idea is to have two components at the same level, in component1 we add the items, keep it in store and in component2 we display the items from the store.
Code for component 1
import React,{useState} from 'react';
import store from "../store/index";
import { connect } from "react-redux";
const Component1 = (props) => {
let [inputTab, handleInputTab] = useState("");
return ( <div>
<input onChange={(e)=>{
handleInputTab(e.target.value);
}}
value={inputTab}
/>
<button onClick={()=>{
props.addItem({inputTab});
console.log(store.getState());
handleInputTab("")
}}>Add</button>
</div> );
}
const mapDispatchToProps = dispatch => {
return {
// dispatching plain actions
addItem: (listItem) => dispatch({ type: 'ADD_ITEM', payload: listItem }),
}
}
export default connect(null,mapDispatchToProps)(Component1);
Code for component 2
import React from 'react';
import { connect } from "react-redux";
const Component2 = (props) => {
if(props.length <= 1){
return <div>tetst</div>
}
return ( <div>
{props.list.map((item, index) => (
item != undefined && <p key={index}>{item.inputTab}</p>
))}
</div>
);
}
const mapStateToProps = state =>{
return {
list: state.list
}
}
export default connect(mapStateToProps)(Component2);
Action
const ADD_ITEM = "ADD_ITEM";
export function addItem(payload) {
return {
type: ADD_ITEM,
payload
};
}
Reducer
const initialState = {
list:[]
}
function addItemReducer(state = initialState, action){
if(action.type="ADD_ITEM"){
return {
list: [...state.list, action.payload]
}
}
return state;
}
export default addItemReducer
Store
import { createStore } from "redux";
import addItemReducer from "../reducers/index"
export default createStore(addItemReducer,);
Problem On console logging the state, I notice an undefined item at 0 index of the list array. I am not sure where it is coming from.
{list: Array(3)}
list: Array(3)
0: undefined
1: {inputTab: "a"}
2: {inputTab: "b"}
length: 3
__proto__: Array(0)
__proto__: Object