React + Redux connect (mapStateToProps) - javascript

I have recently begun to work with React, and I'm enjoying it a lot even though I'm constantly running into problems.
Component #1 where I make a GET-request by a click on a button and I display some data in a table.
Component #2 is a input field, where I want to enter some data, and display it below, should be simple right?
When I dispatch a action, and have finished my GET-request, state looks like this:
{
isFetching: false,
isPressed: true,
items: [{item: 1}, {item: 2}, {item: 3}]
}
Then I want to navigate to my other component. Do I need to unsubscribe to state here? Because when I navigate to my other page, where my other component is, the state will remain.
If I dispatch a action on my component #2 the state looks like this:
[
{id: 1, text: 'foo'},
{id: 2, text: 'bar'}
]
In both components I am using mapStateToPros, even though I don't really understand how it works, and thats where and why I'm running into problems I believe.
function mapStateToProps(state) {
return state;
}
It just returns the state as of now. And when I switch between components, i will get errors messages. If I dispatch a action on my component #2 and then try to navigate to my component #1 (GET-REQUEST) I will get the following:
prev state Object { isFetching=false, isPressed=true, items=[10]}
action Object { type="ADD_TODO", id=0, text="asd"}
next state [Object { id=0, text="asd"}]
Navigates to other page
Error: `mapStateToProps` must return an object. Instead received [object Object].
How should mapStateToProps be used in my scenario?
Do I need to use componentWillUnmount? Do Unsubscribe to my store?
I feel like I could ask a hundred questions, but I won't. I'm constantly reading the documentation but I'm still trying to figure it out.
Any links, advice on thought process, and other useful things are much appriecated.
EDIT:
This is my reducer:
As Ricky suggested below, I need to make my array into a object.
case ADD_TODO:
return [
...state,
todo(undefined, action)
]
const todo = (state = [], action) => {
case ADD_TODO:
return {
id: action.id,
text: action.text
}
}
But, the "spread operator" will not work if I return a object instead of a array. Is there another option then (...) ?

This is an array:
[
{id: 1, text: 'foo'},
{id: 2, text: 'bar'}
]
Make it an object:
{
myData: [
{id: 1, text: 'foo'},
{id: 2, text: 'bar'}
]
}
And don't "unsubscribe" from state. Redux stores all state in one object. Each component selectively declares what properties of state they need within a function (mapStateToProps) supplied to Redux connect().
Edit
In response the the question update - you are passing in an array for the default state. Use an object:
const todo = (state = {}, action) => {
// initialize your default state properties
switch (action.type) {
case ADD_TODO:
return {
...state
id: action.id,
text: action.text
}
default:
return state;
}
}
You might want to initialize default state properties in your reducer. But all this stuff is in the docs/examples.
Oh, and if you're asking me for more advice, it's a courtesy to upvote :)

Related

Redux | Why this store's parameter type changes after second click?

I'm trying to push a new value in the store's state. It works fine the first time I click on the button "Add item", but the second time I got the following error: "state.basket.push is not a function". I configure the action to console log the state and got the following results:
1st click: {...}{basketItems: Array [ "44" ]}
2nd click: Object {basketItems: 0 }
Why the variable type is changing from array to an int?
Here is the code for the rendered component:
function Counter({ basketItems,additem }) {
return (
<div>
<button onClick={additem}>Add item</button>
</div>
);
}
const mapStateToProps = state => ({
basketItems: state.counterReducer.basketItems,
});
const mapDispatchToProps = dispatch => {
return {
additem: ()=>dispatch({type: actionType.ADDITEM, itemName:'Dummy text' }),
};
};
export default connect(
mapStateToProps,
mapDispatchToProps
)(Counter);
And the reducer looks like this:
import {ADDITEM} from "../actions/types";
const initialState = { basket: [], };
export default function reducer(state = initialState, action) {
switch (action.type) {
case ADDITEM:
console.log(state);
// let newBasket = state.basket.push('44');
return {
...state,
basket: state.basket.push('44')
};
default:
return state;
}
}
I'm copying the state before updating the basket to prevent weird behaviors.
There's two problems here:
state.basket.push() mutates the existing state.basket array, which is not allowed in Redux
It also returns the new size of the array, not an actual array
So, you're not doing a correct immutable update, and you're returning a value that is not an array.
A correct immutable update here would look like:
return {
...state,
basket: state.basket.concat("44")
}
Having said that, you should really be using our official Redux Toolkit package, which will let you drastically simplify your reducer logic and catch mistakes like this.

Redux initial state gets mutated even when using Object.assign

This is a simple replication of a problem i encounter in an actual app.
https://jsfiddle.net/zqb7mf61/
Basically, if you clicked on 'Update Todo" button, the text will change from "Clean Room" to "Get Milk". "Clean Room" is a value in the initial State of the reducer. Then in my React Component, I actually try to clone the state and mutate the clone to change the value to "Get Milk" (Line 35/36). Surprisingly, the initial State itself is also mutated even though I try not to mutate it (as seen in line 13 too).
I am wondering why Object.assign does not work for redux.
Here are the codes from the jsFiddle.
REDUX
const initState = {
task: {id: 1, text: 'Clean Room'}
}
// REDUCER
function todoReducer (state = initState, action) {
switch (action.type) {
case 'UPDATE_TODO':
console.log(state)
let newTodo = Object.assign({}, state) // here i'm trying to not make any changes. But i am surpise that state is already mutated.
return newTodo
default:
return state;
}
}
// ACTION CREATORS:
function updateTodo () {
return {type: 'UPDATE_TODO'};
}
// Create Store
var todoStore = Redux.createStore(todoReducer);
REACT COMPONENT
//REACT COMPONENT
class App extends React.Component{
_onSubmit = (e)=> {
e.preventDefault();
let newTodos = Object.assign({}, this.props.todos) // here i clone the redux state so that it will not be mutated, but i am surprise that it is mutated and affected the reducer.
newTodos.task.text = 'Get Milk'
console.log(this.props.todos)
this.props.updateTodo();
}
render(){
return (
<div>
<h3>Todo List:</h3>
<p> {this.props.todos.task.text} </p>
<form onSubmit={this._onSubmit} ref='form'>
<input type='submit' value='Update Todo' />
</form>
</div>
);
}
}
// Map state and dispatch to props
function mapStateToProps (state) {
return {
todos: state
};
}
function mapDispatchToProps (dispatch) {
return Redux.bindActionCreators({
updateTodo: updateTodo
}, dispatch);
}
// CONNECT TO REDUX STORE
var AppContainer = ReactRedux.connect(mapStateToProps, mapDispatchToProps)(App);
You use Object.assign in both the reducer as in the component. This function only copies the first level of variables within the object. You will get a new main object, but the references to the objects on the 2nd depth are still the same.
E.g. you just copy the reference to the task object around instead of actually creating a new task object.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign#Deep_Clone
Apart from that it would be better to not load the whole state into your component and handle actions differently. Lets just solve this for now. You will have to create a new task object in your onSubmit instead of assigning a new text to the object reference. This would look like this:
newTodos.task = Object.assign({}, newTodos.task, {text: 'Get Milk'})
Furthermore to actually update the store, you will have to edit your reducer as you now assign the current state to the new state. This new line would look like this:
let newTodo = Object.assign({}, action.todos)

what is best way to set state in react on component update? My Render method gets the updated data but component does not updates

I have three tabs on top of my orders screen. Its data is like this:
state = {
ordersTabItems: [
{ id: 2, name: 'Incoming', isSelected: false, itemsCount: null },
{ id: 3, name: 'Processing', isSelected: false, itemsCount: null },
{ id: 4, name: 'Completed', isSelected: false, itemsCount: null },
],
activeTab: 'incomming',
inc: '',
};
I am rendering it using a flatlist in my render method. In the render method I also get variables from store like incommingCount, processing Count and CompletedCount. So once the data updates in Tabs, Count values of each tab changes. Which can be seen updated by putting a debugger on render.
I want to update my ordersTabItems on based upon props received from redux store. I don't have any idea which life cycle method should I choose here.
You should use componentWillReceiveProps lifecycle to track changes of props from redux store by comparing this.props and nextProps.
Once you find changes, update state properly which will lead to re-rendering of component. If you put more detailed code and descriptions, I can help you asap.
Once you update the store. You can get updated global state within connected component in componentWillReceiveProps like this :
componentWillReceiveProps(nextProps){
//invoke function with updated store
//this.foo(nextProps) any method you would like to invoke and setState there
console.log(this.props); // prevProps
console.log(nextProps); // currentProps after updating the store
}
And you can also use getDerivedStateFromProps
static getDerivedStateFromProps(nextProps, prevState) {
}
You can create a function like this:
const updateActiveTab = (tabId) => {
this.setState(...this.state, activeTab: tabId)
}
Then you can call the function in the render() method:
this.updateActiveTab(this.props.activeTabId)

Pass by reference assignment mutates redux state

I have an app with a menu of items, and at some point a user may edit the values of the items. When the user does so, I create a copy of the item in a seperate state branch instead of changing the original menu items. So my reducer looks like this:
const menuReducer = (state = [], action) => {
switch (action.type) {
case ADD_ITEM:
return [...state, {id: action.itemId, propA: action.itemPropA, propB: action.itemPropB}]
}
}
const editingMenuItem = (state = {}, action) => {
switch (action.type) {
case SET_EDIT_ITEM:
return {id: action.id, propA: action.itemPropA, propB: action.itemPropB}
case EDIT_ITEM:
return {id: state.id, propA: action.itemPropA, propB: action.itemPropB}
}
}
Someone selects that they want to edit an item, and this causes the dispatchEditItem thunk to trigger and create a copy in the state tree:
const dispatchEditItemThunk = itemId => (dispatch, getState) => {
const item = _.find(getState().menu, ['id', itemId]);
dispatch(setEditItem(item.id, item.propA, item.propB))
}
Then when someone wants to edit a prop, the editingThunk is dispatched:
const editingThunk = (itemId, propName) => (dispatch, getState) => {
let activeItem = getState().editingMenuItem;
// someValue is generated here
activeItem[propName] = someValue
dispatch(editItem(activeItem.propA, activeItem.propB))
}
The problem with this is that when activeItem[propName] = someValue happens, this changes the value of the item contained in the menuReducer array. I'm assuming because everything is pass by reference, and all the references lead back to the original value in the menuReducer. However, this isn't the way I would expect this to work. My assumption would be that calling getState would return a deep copy of the state, and not allow for these kinds of accidental mutations.
Is this a bug? If it isn't, is there a preferred way of writing thunks that avoids this kind of situation? In my real use case, the structure of the props in the menuItem is very complex, and it is handy to create an activeItem in the thunk and mutate it's values before dispatching to the state tree. Is doing this bad?
That's not a bug and mutating state object is highly discouraged. You can create a deep copy of an object using Object.assign and JSON.stringify methods as described here https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign (Examples section).
If Redux was to create a deep copy of state on each dispatch call it could be more secure but also much slower.

redux - reducer state is blank

I am trying to replicate something similar to the TodoList example in the the redux docs' basic example. The second reducer receives an array - styleItems = [{... ... }, {... ...}] - and then calls the first function to act on each of the individual objects.
I provide an initialState to the app container via the following, as shown in containers/app.js. However, the state passed to the styleItems reducer seems to be a blank array - each and every time.
However, react renders the UI based on the initial config, and react dev-tools shows the state structure as expected. Is the redux store somehow seeing the same thing as react?
containers/app.js
function starterInfo(state) {
return {
// The ID of this particular object
id: 12345,
// Various keys and theri css values
styleItems: [
{
pk: 31,
order: 1,
label: 'Caption text color',
css_identifier: '.caption-text',
css_attribute: 'color',
css_value: '#FFFFFF'
},
{
pk:23,
order: 2,
label: 'Caption link color',
css_identifier: '.caption-link',
css_attribute: 'color',
css_value: '#FEFEFE'
}
],
// Network state info
currently_fetching: false,
currently_posting: false
}
}
export default connect(starterInfo)(App)
reducers/index.js
// This handles a single styleItem object within the array
function change_css(state = {}, action){
switch (action.type){
case actions.CHANGE_CSS:
if (state.order !== action.order){
return state
}
return {
...state,
css_value
}
default:
return state
}
}
// This handles the styles array in the global state
function styleItems(state = [], action){
switch(action.type){
case actions.CHANGE_CSS:
const foobar = state.map(styleItem =>
change_css(styleItem, action)
)
return foobar
default:
return state
}
}
The short answer is that you're not passing the initial state quite right. The first argument to the connect function for the React Redux bindings is mapStateToProps. The point of this function is to take the state that already exists in your app and map it to props for your component. What you're doing in your starterInfo function is kind of just hard-coding what the state is for your component. Because you're returning a plain object React doesn't really know the difference so it works just fine, but Redux doesn't yet know about your app state.
Instead, what you should do is provide your initial state directly to the reducers, like this:
const intialStyleItemsState = [
{
pk: 31,
order: 1,
label: 'Caption text color',
css_identifier: '.caption-text',
css_attribute: 'color',
css_value: '#FFFFFF'
},
{
pk:23,
order: 2,
label: 'Caption link color',
css_identifier: '.caption-link',
css_attribute: 'color',
css_value: '#FEFEFE'
}
];
function styleItems(state = intialStyleItemsState, action){ ...
And eventually, because you're splitting your reducers up you'll need to combine them back together again with Redux's combineReducers utility, provide that root reducer to your store and go from there.
You can also pass the initial state using the redux function createstore that take as argument createStore(reducer, [initialState]) http://rackt.org/redux/docs/api/createStore.html
Let’s say you have two reducers
change_css(state = {}, action)
function styleItems(state = [], action)
If you use comibneReducer to initialize your state
var reducer = combineReducers({
css: change_css,
items: styleItems
})
Now
var store = createStore(reducer)
console.log(store.getState())
Your store will contain { css: {}, items: [] }
Now if you want to initialize the state you can pass the initial state as the second argument of the createStore function.
createStore(reducer, {css:{some properties},items:[{name:"obj1"},{name:"obj2"},{name:"obj3"}]})
Now you store will contain the initial state. {css:{some properties,items:[{name:"obj1"},{name:"obj2"},{name:"obj3"}]}
You can feed this state from server for example and set it as initial state of your application

Categories

Resources