function addTodoWithDispatch(text) {
const action = {
type: ADD_TODO,
text
}
dispatch(action)
}
http://redux.js.org/docs/basics/Actions.html#action-creators
I saw the code above from redux documentation. What I don't understand is the text in the action. It doesn't look like a valid javascript object or array syntax. Is it an ES6 new syntax? Thanks.
It is just a new ES6 syntax, which simplifies creating properties on the literal syntax
In short, if the name is the same as the property, you only have to write it once
So this would be exactly the same :)
function addTodoWithDispatch(text) {
const action = {
type: ADD_TODO,
text: text
}
dispatch(action)
}
In the above code
function addTodoWithDispatch(text) {
const action = {
type: ADD_TODO,
text
}
dispatch(action)
}
here text is an example of object literal shorthand notation. ES6 gives you a shortcut for defining properties on an object whose value is equal to another variable with the same key.
As has been said this is just shorthand for writing
const action = {
type: ADD_TODO,
text: text
}
dispatch(action)
Have a look at this blog
If you look at the next page in document http://redux.js.org/docs/basics/Reducers.html
function todoApp(state = initialState, action) {
switch (action.type) {
case SET_VISIBILITY_FILTER:
return Object.assign({}, state, {
visibilityFilter: action.filter
})
case ADD_TODO:
return Object.assign({}, state, {
todos: [
...state.todos,
{
text: action.text,
completed: false
}
]
})
case TOGGLE_TODO:
return Object.assign({}, state, {
todos: state.todos.map((todo, index) => {
if(index === action.index) {
return Object.assign({}, todo, {
completed: !todo.completed
})
}
return todo
})
})
default:
return state
}
}
It is expecting property name text. As #Icepickle mentioned it is a valid format but you can also change to below format:
function addTodoWithDispatch(text) {
const action = {
type: ADD_TODO,
text:text
}
dispatch(action)
}
Related
I'm working on my first solo ReactJS/Redux project and things were going well until I got to a point where I'm using an object in the Redux store that is always supposed to be a single object. When I copy the object from one part of the store (one element of the sources key) to another (the selectedItems key) that object is being stored as an array of length 1, which isn't the data I'm passing in (it's just a single object). I could live with this and just read out of that store variable as an array and just use element 0 except that when I call another method in the reducer to replace that variable in the store, that method stores the new data as a single object! My preference would be to have everything store a single object but I can't figure out how to do that. Anyway, here's some of the reducer code:
const initialState = {
sources: [
{
id: 1,
mfg: 'GE',
system: 'Smart bed',
model: '01',
name: 'GE smart bed'
},
{
id: 2,
mfg: 'IBM',
system: 'Patient monitor',
model: '03',
name: 'IBM patient monitor'
}
],
error: null,
loading: false,
purchased: false,
selectedItem: {}
};
// This is called when a user selects one of sources in the UI
// the Id of the selected sources object is passed in as action.id
// This method creates an array in state.selectedItem
const alertSourceSelect = ( state, action ) => {
let selectedItem = state.sources.filter(function (item) {
return item.id === action.id;
});
if (!selectedItem) selectedItem = {};
return {...state, selectedItem: selectedItem};
};
// When someone edits the selected source, this takes the field name and new value to
// replace in the selected source object and does so. Those values are stored in
// action.field and action.value . However, when the selected source object is updated
// it is updated as a single object and not as an array.
const selectedSourceEdit = ( state, action ) => {
return {
...state,
selectedItem: updateObject(state.selectedItem[0], { [action.field] : action.value })
};
};
const reducer = (state = initialState, action) => {
switch (action.type) {
case actionTypes.ALERT_SOURCE_SELECT: return alertSourceSelect( state, action );
case actionTypes.ALERT_SELECTED_SOURCE_EDIT: return selectedSourceEdit( state, action );
default: return state;
}
Here is the updateObject method (sorry I left it out):
export const updateObject = (oldObject, updatedProperties) => {
return {
...oldObject,
...updatedProperties
}
};
Issue : updateObject is returning object and not array,and you are maintaining selectedItem as an array not object
export const updateObject = (oldObject, updatedProperties) => {
return {
...oldObject,
...updatedProperties
}
};
Solution :
Either return array from updateObject :
export const updateObject = (oldObject, updatedProperties) => {
return [{
...oldObject,
...updatedProperties
}]
};
OR make array of returned object
const selectedSourceEdit = ( state, action ) => {
return {
...state,
selectedItem: [updateObject(state.selectedItem[0], { [action.field] : action.value })]
};
};
How do i write this inside of an reducer to change the state?
doc = {
id:"zf123ada123ad",
name:"examp",
subdoc:{
name:"subdoc examp",
subsubdoc:[{
id:"zcgsdf123zaar21",
subsubsubdoc:[{
id:"af2317bh123",
value: "heyhey" //this value I want to update
}]
}]
}
}
let's say i have an reducer that looks like this
The action.payload look something like this
{
theInputId1: "someId",
theInputId2: "anotherId",
theInputValue: "someValue"
}
export function updateSubSubSubDoc(state = {}, action){
switch(action.type){
case 'UPDATE_THE_SUBSUBSUB':
return {
state.doc.subdoc.subsubdoc.find(x => x.id ==
theInputId1).subsubsubdoc.find(x => x.id == theInputId2).value = theInputValue // just example code for you to understand where i'm going.
}
default:
return state
}
}
What I want to do it update one subsubsub doc in a state that is current
With ES6, this is one way that you could do that:
const initialState = { doc: { subdoc: { subsubdoc: {} } } };
export function doc(state = initialState, action) {
switch (action.type) {
case 'UPDATE_THE_SUBSUBSUB':
const subsubdocIdx = state.doc.subdoc.
subsubdoc.find(s => s.id == action.theInputId1);
const subsubdoc = state.doc.subdoc.subsubdoc[subsubdocIdx];
const subsubsubdocIdx = state.doc.subdoc.
subsubdoc[subsubdocIdx].
subsubsubdoc.find(s => s.id == action.theInputId2);
const subsubsubdoc = state.doc.subdoc.
subsubdoc[subsubdocIdx].
subsubsubdoc[subsubsubdocIdx];
return {
...state,
doc: {
...state.doc,
subdoc: {
...state.doc.subdoc,
subsubdoc: [
...state.doc.subdoc.subsubdoc.slice(0, subsubdocIdx),
{
...subsubdoc,
subsubsubdoc: [
...subsubdoc.slice(0, subsubsubdocIdx),
{
...subsubsubdoc,
value: action.theInputValue,
},
...subsubdoc.subsubsubdoc.slice(subsubsubdocIdx + 1, subsubdoc.subsubsubdoc.length - 1),
],
},
...state.doc.subdoc.subsubdoc.slice(subsubdocIdx + 1, state.doc.subdoc.subsubdoc.length - 1),
]
}
}
}
default:
return state;
}
}
(I haven’t tested this code.)
This is nested the same level as in your example, but you might consider using something like combineReducers to make this a little easier to manage. This is also presupposing you have other actions that create the document chain along the way, and you know these documents exist.
Here's an example how you might be able to do it with combineReducers:
function doc(state = {}, action) {
}
function subdoc(state = {}, action) {
}
function subsubdoc(state = [], action) {
}
function subsubsubdoc(state = [], action) {
switch (action.type) {
case 'UPDATE_THE_SUBSUBSUB':
const idx = state.find(s => s.id == action.theInputId2);
return [
...state.slice(0, idx),
{
...state[idx],
value: action.theInputValue,
},
...state.slice(idx + 1),
];
default:
return state;
}
}
export default combineReducers({
doc,
subdoc,
subsubdoc,
subsubsubdoc,
});
In this example, you don't need action.theInputId1, but you would need to store some reference in the data from the subsubdoc to the subsubsubdoc so that when you're rendering, you can piece it back together. Same with all of the other layers.
I call a function with this code,
gqlActions('customer', 'Add', this.props, values);
or
gqlActions('customer', 'Update', this.props, values);
this funcions is used for add and update actions.
On the function I use computed property, for example in
const tableAction= `${table}${action}`;
[tableAction]: valuesOptimistic,
It's working ok, my problem is in destructuring before, to use that variable after:
update: (store, { data: { [tableAction] }}) => {
data.customers.push([tableAction]);
it's not valid syntax... , before i've used hardcode for 'Add' action :
update: (store, { data: { customerAdd }}) => {
data.customers.push(customerAdd);
},
or
update: (store, { data: { customerUpdate }}) => {
data.customers.push(customerUpdate);
},
becase I send 'update' property to work for a library that sends me the value accord to [tableAction] that I've defined in:
optimisticResponse: {
[tableAction]: valuesOptimistic,
}
I mean parameter in denormalization is variable (update or add). I hope be clear.
my full function:
export const gqlActions = (table, action, props, values) => {
const valuesOptimistic = {
...Object.assign({}, values, __typename: table'})
};
const tableAction= `${table}${action}`;
props.mutate(
{
variables: values,
optimisticResponse: {
[tableAction]: valuesOptimistic,
},
update: (store, { data: { [tableAction] }}) => {
data.customers.push([tableAction]);
},
},
)
}
}
You need to use destructuring using computed property names
update: (store, { data: { [tableAction]:action }}) => {
data.customers.push(action);
}
I am doing pagination where i will be getting data for each page click.I want to append the data with the previous values.Here is my current code.Have no idea to do it.
const InitialProjects={
projectList:[],
error:null,
loading:false
}
export const projects=(state=InitialProjects,action)=>{
switch(action.type){
case ActionTypes.FETCH_PROJECTS:
return Object.assign({},state,{
projectList:[],error:null,loading:true
})
case ActionTypes.FETCH_PROJECTS_SUCCESS:
return {
projectList:action.payload
}
case ActionTypes.FETCH_PROJECTS_FAILURE:
return Object.assign({},state,{
projectList:["not-found"],error:action.payload.message||action.payload.status,loading:false
})
default:
return state;
}
}
My first response will look something like this
[
{
Id:0,
Name:india
},
{
Id:1,
Name:bang
},
{
Id:3,
Name:us
},
{
Id:5,
Name:uk
}
]
second response will be like this
[
{
Id:8,
Name:india
},
{
Id:12,
Name:bang
},
{
Id:19,
Name:us
},
{
Id:35,
Name:uk
}
]
Please do note that the id field might not be consecutive.
I want something like this in my redux
projectList:
0(pin): {Id:1,Name:'dewd'}
1(pin): {Id:2,Name:'tyytg'}
2(pin): {Id:5,Name:'xsx'}
3(pin): {Id:4,Name:'tyyt'}
4(pin): {Id:10,Name:'xsx'}
5(pin): {Id:17,Name:'xsx'}
Appreciate any help.Thanks
You can spread the results on each success.
case ActionTypes.FETCH_PROJECTS:
return {
...state,
error: null,
loading: true,
}
case ActionTypes.FETCH_PROJECTS_SUCCESS:
return {
...state,
projectList: [...state.projectList, ...action.payload]
}
Looks like the object spread operator doesn't work in your case. So an ES5 version of the answer for you would be.
case ActionTypes.FETCH_PROJECTS_SUCCESS:
return Object.assign(
{},
state,
{
projectList: state.projectList.concat(action.payload)
});
This copies all the previous values from state into a new object by using Object.assign then overwrites a new projectList property by concatenating old values from state.projectList and new ones from action.payload.
Hope it helps!
I have a reducer working with an object with arrays. I want to change a value on the nested arrays based on a given index. This code works but I can't seem to get my test to work using deep freeze. I was trying to look at the redux example here http://redux.js.org/docs/basics/Reducers.html using .map to find the index with no luck. Any ideas?
export default function myReducer(state = { toDisplay: [] }, action) {
const { type, groupIndex, itemIndex } = action;
const newObject = Object.assign({}, state);
switch (type) {
case actionTypes.TOGGLE_GROUP:
newObject.toDisplay[groupIndex].isSelected = newObject.toDisplay[groupIndex].isSelected ? false : 'selected';
return newObject;
case actionTypes.TOGGLE_ITEM:
newObject.toDisplay[groupIndex].values[itemIndex].isSelected = newObject.toDisplay[groupIndex].values[itemIndex].isSelected ? false : true;
return newObject;
default:
return state;
}
}
EDIT:
For anyone curious after watching a helpful redux video I came up with this:
export default function myReducer(state = { toDisplay: [] }, action) {
const { type, groupIndex, itemIndex } = action;
switch (type) {
case actionTypes.TOGGLE_GROUP:
return {
...state,
toDisplay: [
...state.toDisplay.slice(0, groupIndex),
{
...state.toDisplay[groupIndex],
isSelected: state.toDisplay[groupIndex].isSelected ? false : 'selected'
},
...state.toDisplay.slice(groupIndex + 1)
]
};
case actionTypes.TOGGLE_ITEM:
return {
...state,
toDisplay: [
...state.toDisplay.slice(0, groupIndex),
{
...state.toDisplay[groupIndex],
values: [
...state.toDisplay[groupIndex].values.slice(0, itemIndex),
{
...state.toDisplay[groupIndex].values[itemIndex],
isSelected: state.toDisplay[groupIndex].values[itemIndex].isSelected ? false : true
},
...state.toDisplay[groupIndex].values.slice(itemIndex + 1)
]
},
...state.toDisplay.slice(groupIndex + 1)
]
};
default:
return state;
}
}
Using a helper/library like suggested is probably the best route but my team wishes to not add another dependency.
Firstly, Object.assign(...) only does a shallow copy. See here.
As you have objects nested inside arrays nested inside objects I would highly recommend the immutability helpers from react (as mentioned by Rafael). These allow you to do something like this:
case actionTypes.TOGGLE_GROUP:
return update(state, {
toDisplay: {
[groupIndex]: {
isSelected: {$set: newObject.toDisplay[groupIndex].isSelected ? false : 'selected'}
}
}
});
If you are looking to modify a simple value inside an array with raw js then you can use something like this:
return list
.slice(0,index)
.concat([list[index] + 1])
.concat(list.slice(index + 1));
(source)