Reputation: 107
The goal of this app is to let met add an item in a Flatlist
present in the List Item screen, using React-Redux
and React Navigation
. Basically I type name and category in the Create Item screen and send it in the form of an array to the List Item screen with React Navigation, and once I'm in the List Item screen I use componentDidMount
to dispatch the action and update the state in the class compoment, the problem is that nothing shows up, even using the console.log
it just gives me back the empty array present in the Redux Reducers screen.
CREATE ITEM SCREEN
export class item extends Component {
constructor(props) {
super(props);
this.state = {
name: '',
category: '',
};
}
submitItem = (name, category) => {
this.props.navigation.navigate("ListItem", {
itemList: {
name: name,
category: category,
}});
};
render() {
const { name, category } = this.state;
return (
<Container>
<Header>
<Left>
<Button onPress={() =>
this.submitItem(
this.state.name,
this.state.category,
)
}>
<Text>Sumbit</Text>
</Button>
ITEM LIST SCREEN
class ListItem extends Component {
constructor(props) {
super(props);
this.state = {
itemList:[],
};
}
componentDidMount (props, state) {
if (this.props.route.params?.itemList) {
() => this.props.dispatch({type:'ADD_ITEM'});
}
return null;
}
REDUX REDUCER
const initialState = {
currentUser: null,
itemList: [],
};
export const user = (state = initialState, action) => {
switch (action.type){
case USER_STATE_CHANGE:
return {
...state,
currentUser: action.currentUser,
};
case 'ADD_ITEM':
return{
itemList: state.itemList,
}
default:
return state
}
};
Upvotes: 0
Views: 357
Reputation: 1186
I think when you are dispatching an action you are not adding the action.payload to the state.itemList.What I meant
const initialState = {
currentUser: null,
itemList: [],
};
export const user = (state = initialState, action) => {
switch (action.type){
case USER_STATE_CHANGE:
return {
...state,
currentUser: action.currentUser,
};
case 'ADD_ITEM':
return{
...state,
itemList: addItemToList(state.itemList,action.payload), //a util function to add items to the list.
// And action.payload is the value ,which passed when you are dispatching the action 'ADD_ITEM'
}
default:
return state
}
};
And when you are dispatching the action it should be
componentDidMount (props, state) {
if (this.props.route.params?.itemList) {
() => this.props.dispatch({type:'ADD_ITEM',payload:this.props.route.params.itemList});
// passing the itemList to as the payload of the action.
}
return null;
}
I guess this modification should suffice. More on React-Redux here
Upvotes: 2