Redux -> How can I save multiple objects in a single store? - reactjs

So I have an app that, whenever I push a button it adds objects to the redux store, the thing is that whenever I press that button the store doesn't really hold the items that I've added but it actually just replaces them, how can I make it so that when I press the button it saves the object inside of it, then on the second click it adds the next object and so on.
Here's my code:
That's where my button is:
{item.map(product => (
<div>
<h1>{product.name}</h1>
<h2>{product.Price}</h2>
<button onClick={() => buyProduct(product)}>
Buy
</button>
</div>
)}
That's where my buyProduct function is:
const buyProduct = (item) => {
store.dispatch({type:"buy", payload: item})
}
And that is all of my redux code:
const reducer = (state, action) => {
if (action.type === 'buy') {
return action.payload;
} else if (action.type === 'Decrease') {
return action.payload
}
return state;
}
const store = createStore(reducer, 0)
store.subscribe(()=>{
console.log('Store is now: ', store.getState())
})
const buyProduct = (item) => {
store.dispatch({type:"buy", payload: item})
}
How can I also make it so that I could loop over the store's stored objects

in the reducer you should add the new data to the current data. if your cart-data is an array of objects, you should push the new product object to the array. for example :
if(action.type==='buy')
{
return {...state, cartArray: [...state.cartArray, action.payload] };
}
and the same logic in the Decrease action.

Related

Why cant I remove element from array in Reactjs with redux

I am dynamically adding <div> elements to a component by adding them to an array. This is not a problem and works well. The issue I'm trying to solve here is removing the <div> on double click by passing the id of the <div> that was doubled clicked with props when the reducer is dispatched.
The main issue is the array filter function only works when I code hard the div id both on the div and in the filter function when I want to pass the id of e.target.id on dispatch of delDiv reducer.
Note: I can remove the div successfully by changing the addDivReducer like this:
case "ADD_DIV":
return state.concat(
<DivComponent
key={Math.floor(Math.random() * 100) + 1}
id={11} ***************************************************** Changed
/>
);
case "DELETE_DIV":
state = state.filter((elements) => {
return elements.props.id !== 11; *********************************** Changed
});
return state;
But the desired effect is to pass id as props on dispatch as seen in my code below
The reducer that adds a removes elements look like this:
import DivComponent from "../../components/AddDivComponent";
const addDivReducer = (state, action) => {
switch (action.type) {
case "ADD_DIV":
return state.concat(
<DivComponent
key={Math.floor(Math.random() * 100) + 1}
id={Math.floor(Math.random() * 100) + 1}
/>
);
case "DELETE_DIV":
state = state.filter((elements) => {
return elements.props.id !== action.payload;
});
return state;
default:
return (state = []);
}
};
export default addClipartReducer;
The actions index.js look like:
export const addDiv = (props) => {
return {
type: "ADD_DIV",
payload: props,
};
};
export const deleteDiv = (props) => {
return {
type: "DELETE_DIV",
payload: props,
};
};
The delete reducer is being dispatched when the div is double clicked on like this in AddDivComponent.js:
import { useDispatch } from "react-redux";
import { deleteDiv } from "../../store/actions";
const AddDivComponent = (props) => {
const dispatch = useDispatch();
const removeClipart = (e) => {
dispatch(deleteDiv(e.target.id));
};
return(
<div
id={props.id}
className="my-div"
onDoubleClick={removeDiv}
/>
);
};
export default DivComponent;
Finally the array of <div> elements is being shown here in Canvas.js:
import { useSelector } from "react-redux";
const Canvas = () => {
const divList = useSelector((state) => state.addDIV);
return(
<div className="canvas">
{divList}
</div>
);
};
export default Canvas;
you are mutating state at your DELETE_DIV reducer. If you need to handle state, create a copy a first:
// mutating state here to a new value, can lead to problems
state = state.filter((elements) => {
return elements.props.id !== action.payload;
});
I would suggest to return filter directly, given filter already returns the desired next state, while not mutating the original:
case "DELETE_DIV":
return state.filter((elements) => {
return elements.props.id !== action.payload;
});

React Native modal is not updated when Redux state is changed using hooks

I have a modal component in my React Native mobile app. It receives an array of objects from Redux state. I can delete a specific item in the array using dispatching an action using useDispatch hook. However, after sending the delete action, the component state is not updated automatically, so that I have to reopen the modal every time to see the updated list.
How can I set the modal to automatically re-render when the redux state is changed using dispatch?
SelectedItems.js
const SelectedItems = () => {
const vegetables = useSelector(state => state.new_order.vegetables)
return (
<Modal visible={isVisible}>
{vegetables.map( (v,index) =>
<VegeItem
key={index}
index={index}
name={v.name}
qty={v.qty}
metric={v.metric}
removeItem={(index) => {
dispatch({
type: 'DELETE_VEGE',
id: index
})
}}
/>)}
</View>
</Modal>
)
}
newOrderReducer.js
const newOrderReducer = (state = INITIAL_STATE, action) => {
switch (action.type) {
case 'ADD_VEGE':
let updatedList = [...state.vegetables,action.vege]
return {
...state,
vegetables: updatedList
}
case 'DELETE_VEGE':
let newVegeList = state.vegetables
newVegeList.splice(action.id,1)
return {
...state,
vegetables: newVegeList
}
default:
return state
}
};
while doing like so let newVegeList = state.vegetables, newVegeList is just a pointer on your state and not a shallow copy of it. Therefore, you still can't mutate it as you can't mutate state outside the return part of the reducer.
so you can do like let newVegeList = [...state.vegetables], or directly at the return
return {
...state,
vegetables: state.vegetables.filter((veg, i) => i != action.id)
}
you can also send veg name or whatever and modify the checker at filter

How to change a value inside array of object in Redux

I have stored an array of object in Redux State and inside each object there is a key named price. Now when I increment the quantity button I need to access the object that has the key inside redux and change the price value. I was able to do that but it's not working properly the price is being changed but a new object is being added in the state of Redux you can see it in the screenshot below. hope I was able to explain the problem clearly. if not please let know so I can explain more.
Cart Component
increment(e, item){
let qty = e.target.previousElementSibling.textContent;
qty++;
e.target.previousElementSibling.textContent = qty;
this.props.changePrice(item);
}
<div>
<input onClick={(e) =>this.decrement(e)} type="submit" value="-"/>
<span>1</span>
<input onClick={(e) => this.increment(e, item)} type="submit" value="+"/>
</div>
function mapStateToProps(state){
return({
itemlist: state.rootReducer
})
}
function mapDispatchToProps(dispatch) {
return({
removeItem: (item)=>{
dispatch({type: 'removeCart', payload: item})
},
changePrice: (item)=>{
dispatch({type: 'changePrice', payload: item})
}
})
}
export default connect(mapStateToProps, mapDispatchToProps)(Cart);
Reducer Component
const changePrice = (itemArray, item)=>{
let newObject = {};
let filteredObject = itemArray.filter(reduxItem => reduxItem.id === item.id);
let newprice = filteredObject[0].price + filteredObject[0].price;
filteredObject[0].price = newprice;
newObject = filteredObject;
const something = ([...itemArray, newObject]);
return something;
}
const reducer = (state = [], action) =>{
switch (action.type) {
case 'Add':
return [...state, action.payload]
case 'removeCart':
const targetItemIndex = state.indexOf(action.payload);
return state.filter((item, index) => index !== targetItemIndex)
case 'changePrice':
return changePrice(state, action.payload)
default:
return state;
}
}
export default reducer;
filteredObject is an array. You override the newObject to be an array in this statement newObject = filteredObject. So the newObject is an array ( in [...itemArray, newObject] ) rather than an object. Keep things simple without unnecessary complexity.You can use Array.map. So do this instead
const changePrice = (itemArray, item) => {
return itemArray.map(reduxItem => {
if(reduxItem.id === item.id){
reduxItem.price = reduxItem.price + reduxItem.price
}
return reduxItem
});
};
See this for more info https://redux.js.org/recipes/structuring-reducers/immutable-update-patterns#inserting-and-removing-items-in-arrays
Hope this helps!
Instead of mutating the state.
// use this
const newState = Object.assign({},state);
We can create a new state and now if you do this, this works fine.
This avoids mutating state.

Implementing infinite scroll with React/Redux and react-waypoint issue

Im struggling to achieve infinite scroll with my test React/Redux application.
Here how it works in simple words:
1) On componentDidMount I dispatch an action which sets the Redux state after getting 100 photos from the API. So I got photos array in Redux state.
2) I implemented react-waypoint, so when you scroll to the bottom of those photos it fires a method which dispatches another action that get more photos and "appends" them to the photos array and...
as I understand - the state changed, so redux is firing the setState and the component redraws completely, so I need to start scrolling again but its 200 photos now. When I reach waypoint again everything happens again, component fully rerenders and I need to scroll from top through 300 photos now.
This is not how I wanted it to work of course.
The simple example on react-waypoint without Redux works like this:
1) you fetch first photos and set the components initial state
2) after you scroll to the waypoint it fires a method which makes another request to the api, constructs new photos array(appending newly fetched photos) and (!) call setState with the new photos array.
And it works. No full re-renders of the component. Scroll position stays the same, and the new items appear below waypoint.
So the question is — is the problem I experience the problem with Redux state management or am I implementing my redux reducers/actions not correctly or...???
Why is setting component state in React Waypoint Infinite Scroll example (no Redux) works the way I want (no redrawing the whole component)?
I appreciate any help! Thank you!
The reducers
import { combineReducers } from 'redux';
const data = (state = {}, action) => {
if (action.type === 'PHOTOS_FETCH_DATA_SUCCESS') {
const photos = state.photos ?
[...state.photos, ...action.data.photo] :
action.data.photo;
return {
photos,
numPages: action.data.pages,
loadedAt: (new Date()).toISOString(),
};
}
return state;
};
const photosHasErrored = (state = false, action) => {
switch (action.type) {
case 'PHOTOS_HAS_ERRORED':
return action.hasErrored;
default:
return state;
}
};
const photosIsLoading = (state = false, action) => {
switch (action.type) {
case 'PHOTOS_IS_LOADING':
return action.isLoading;
default:
return state;
}
};
const queryOptionsIntitial = {
taste: 0,
page: 1,
sortBy: 'interestingness-asc',
};
const queryOptions = (state = queryOptionsIntitial, action) => {
switch (action.type) {
case 'SET_TASTE':
return Object.assign({}, state, {
taste: action.taste,
});
case 'SET_SORTBY':
return Object.assign({}, state, {
sortBy: action.sortBy,
});
case 'SET_QUERY_OPTIONS':
return Object.assign({}, state, {
taste: action.taste,
page: action.page,
sortBy: action.sortBy,
});
default:
return state;
}
};
const reducers = combineReducers({
data,
photosHasErrored,
photosIsLoading,
queryOptions,
});
export default reducers;
Action creators
import tastes from '../tastes';
// Action creators
export const photosHasErrored = bool => ({
type: 'PHOTOS_HAS_ERRORED',
hasErrored: bool,
});
export const photosIsLoading = bool => ({
type: 'PHOTOS_IS_LOADING',
isLoading: bool,
});
export const photosFetchDataSuccess = data => ({
type: 'PHOTOS_FETCH_DATA_SUCCESS',
data,
});
export const setQueryOptions = (taste = 0, page, sortBy = 'interestingness-asc') => ({
type: 'SET_QUERY_OPTIONS',
taste,
page,
sortBy,
});
export const photosFetchData = (taste = 0, page = 1, sort = 'interestingness-asc', num = 500) => (dispatch) => {
dispatch(photosIsLoading(true));
dispatch(setQueryOptions(taste, page, sort));
const apiKey = '091af22a3063bac9bfd2e61147692ecd';
const url = `https://api.flickr.com/services/rest/?api_key=${apiKey}&method=flickr.photos.search&format=json&nojsoncallback=1&safe_search=1&content_type=1&per_page=${num}&page=${page}&sort=${sort}&text=${tastes[taste].keywords}`;
// console.log(url);
fetch(url)
.then((response) => {
if (!response.ok) {
throw Error(response.statusText);
}
dispatch(photosIsLoading(false));
return response;
})
.then(response => response.json())
.then((data) => {
// console.log('vvvvv', data.photos);
dispatch(photosFetchDataSuccess(data.photos));
})
.catch(() => dispatch(photosHasErrored(true)));
};
I also include my main component that renders the photos because I think maybe it's somehow connected with the fact that i "connect" this component to Redux store...
import React from 'react';
import injectSheet from 'react-jss';
import { connect } from 'react-redux';
import Waypoint from 'react-waypoint';
import Photo from '../Photo';
import { photosFetchData } from '../../actions';
import styles from './styles';
class Page extends React.Component {
loadMore = () => {
const { options, fetchData } = this.props;
fetchData(options.taste, options.page + 1, options.sortBy);
}
render() {
const { classes, isLoading, isErrored, data } = this.props;
const taste = 0;
const uniqueUsers = [];
const photos = [];
if (data.photos && data.photos.length > 0) {
data.photos.forEach((photo) => {
if (uniqueUsers.indexOf(photo.owner) === -1) {
uniqueUsers.push(photo.owner);
photos.push(photo);
}
});
}
return (
<div className={classes.wrap}>
<main className={classes.page}>
{!isLoading && !isErrored && photos.length > 0 &&
photos.map(photo =>
(<Photo
key={photo.id}
taste={taste}
id={photo.id}
farm={photo.farm}
secret={photo.secret}
server={photo.server}
owner={photo.owner}
/>))
}
</main>
{!isLoading && !isErrored && photos.length > 0 && <div className={classes.wp}><Waypoint onEnter={() => this.loadMore()} /></div>}
{!isLoading && !isErrored && photos.length > 0 && <div className={classes.wp}>Loading...</div>}
</div>
);
}
}
const mapStateToProps = state => ({
data: state.data,
options: state.queryOptions,
hasErrored: state.photosHasErrored,
isLoading: state.photosIsLoading,
});
const mapDispatchToProps = dispatch => ({
fetchData: (taste, page, sort) => dispatch(photosFetchData(taste, page, sort)),
});
const withStore = connect(mapStateToProps, mapDispatchToProps)(Page);
export default injectSheet(styles)(withStore);
Answer to Eric Na
state.photos is an object and I just check if its present in the state. sorry, in my example I just tried to simplify things.
action.data.photo is an array for sure. Api names it so and I didn't think about renaming it.
I supplied some pics from react dev tools.
Here is my initial state after getting photos
Here is the changed state after getting new portion of photos
There were 496 photos in the initial state, and 996 after getting
additional photos for the first time after reaching waypoint
here is action.data
So all I want to say that the photos are fetched and appended but it triggers whole re-render of the component still...
I think I see the problem.
In your component you check for
{!isLoading && !isErrored && photos.length > 0 &&
photos.map(photo =>
(<Photo
key={photo.id}
taste={taste}
id={photo.id}
farm={photo.farm}
secret={photo.secret}
server={photo.server}
owner={photo.owner}
/>))
}
once you make another api request, in your action creator you set isLoading to true. this tells react to remove the whole photos component and then once it's set to false again react will show the new photos.
you need to add a loader at the bottom and not to remove the whole photos component once fetching and then render it again.
EDIT2
Try commenting out the whole uniqueUsers part (let's worry about the uniqueness of the users later)
const photos = [];
if (data.photos && data.photos.length > 0) {
data.photos.forEach((photo) => {
if (uniqueUsers.indexOf(photo.owner) === -1) {
uniqueUsers.push(photo.owner);
photos.push(photo);
}
});
}
and instead of
photos.map(photo =>
(<Photo ..
try directly mapping data.photos?
data.photos.map(photo =>
(<Photo ..
EDIT
...action.data.photo] :
action.data.photo;
can you make sure it's action.data.photo, not action.data.photos, or even just action.data? Can you try logging the data to the console?
Also,
state.photos ? .. : ..
Here, state.photos will always evaluate to true-y value, even if it's an empty array. You can change it to
state.photos.length ? .. : ..
It's hard to tell without actually seeing how you update photos in reducers and actions, but I doubt that it's the problem with how Redux manages state.
When you get new photos from ajax request, the new photos coming in should be appended to the end of the photos array in the store.
For example, if currently photos: [<Photo Z>, <Photo F>, ...] in Redux store, and the new photos in action is photos: [<Photo D>, <Photo Q>, ...], the photos in store should be updated like this:
export default function myReducer(state = initialState, action) {
switch (action.type) {
case types.RECEIVE_PHOTOS:
return {
...state,
photos: [
...state.photos,
...action.photos,
],
};
...

Redux store is updated but UI is not

I'm having an issue with my vote score on comments. I can see in Redux Devtool that the value has changed but I need to force reload to update the UI.
Not sure why this is. I get my comments as an object with a key of the parent elements id as a key and an array inside of it.
This is then converted inside of mapStateToProps.
Heres an image showing different stages of comments.
Anyone have any idea why this is.
Cheers, Petter
Action
export function pushVoteComment(option, postId) {
const request = API.commentPostVote(option, postId)
return dispatch => {
request.then(({ data }) => {
dispatch({ type: COMMENTS_POST_VOTE, payload: data, meta: postId })
})
}
}
Reducer
const comments = (state = {}, action) => {
switch (action.type) {
case COMMENTS_GET_COMMENTS:
return {
...state,
[action.meta]: action.payload,
}
case COMMENTS_POST_VOTE:
console.log('An vote request was sent returning ', action.payload)
return { ...state, [action.payload.id]: action.payload }
default:
return state
}
}
PostDetailes ( its used here to render a PostComment )
renderComments() {
const { comments, post } = this.props
console.log('This post has these comments: ', comments)
return _.map(comments, comment => {
return (
<div key={comment.id} className="post-container">
{post ? (
<PostComment
key={comment.id}
postId={comment.id}
body={comment.body}
author={comment.author}
voteScore={comment.voteScore}
timestamp={comment.timestamp}
/>
) : (
''
)}
</div>
)
})
}
const mapStateToProps = (state, ownProps) => {
const { posts, comments } = state
return {
comments: comments[ownProps.match.params.postId],
post: posts.filter(
item => item.id === ownProps.match.params.postId && item.deleted !== true
)[0],
}
}
PostComment
<i
className="fa fa-chevron-up"
aria-hidden="true"
onClick={() => pushVoteComment('upVote', postId)}
/>
<span className="vote-amount">{voteScore}</span>
<i
className="fa fa-chevron-down"
onClick={() => pushVoteComment('downVote', postId)}
/>
export default connect(null, { pushVoteComment })(PostComment)
PS:
The reason it is built with a {parentId: [{comment1}, {comment2}]}
Is that I use it when showing all posts to see a number of comments.
return ({comments.length})
const mapStateToProps = (state, ownProps) => {
return {
comments: state.comments[ownProps.postId]
? state.comments[ownProps.postId]
: [],
}
}
Redux dev tool
Looks like this when I press the votebutton for the first time:
Then when I press again I get this:
The issue here is that it's changing the state, not thinking about the fact that I have my comment stored as
{
[postId]: [array of comments]
}
So in order to resolve it, I ended up rewriting my reducer doing it like this.
case COMMENTS_POST_VOTE:
const { parentId } = action.payload // get commentId
const commentList = [...state[parentId]] // get array of comments, but copy it
const commentIndex = commentList.findIndex(el => (el.id === payload.id)) // get index of comment
commentList[commentIndex] = action.payload // update the commentList
const updatedPost = {...state, [parentId]: commentList} // return new state
return updatedPost

Resources