Is there a more concise, prettier way to write this snippet of code? Learning es6 syntactic sugar and was wondering if i can reduce the number of lines for this snippet
const checkLoggedInSuccess = ({
user,
}: {
user?: User;
}): AuthenticationActionTypes => {
if (user === undefined) {
return {
type: CHECK_LOGGED_IN_SUCCESS,
isFetching: false,
};
} else {
return {
type: CHECK_LOGGED_IN_SUCCESS,
isFetching: false,
user: {
email: user.email,
},
};
}
};
how'd'ya fancy this?
const checkLoggedInSuccess = ({user}: {user?: User}): AuthenticationActionTypes => (
!!user
? {
type: CHECK_LOGGED_IN_SUCCESS,
isFetching: false,
}
: {
type: CHECK_LOGGED_IN_SUCCESS,
isFetching: false,
user: {
email: user.email,
},
}
)
Related
i have table model User
const schema = new mongoose.Schema(
{
telegramId_parent: {
type: Number,
default: null,
},
telegramId: {
type: Number,
required: true,
unique: true,
},
telegramName: {
type: String,
},
},
{ timestamps: true }
);
So I can find the first level
User.find({ telegramId_parent: id })
.then((user) => {
resolve(user);
})
.catch((err) =>
);
accordingly, after I can make the same query for the result through recursion 5 times.
maybe there is another way? better? can the data be stored differently?
I have a question I am making React app. The thing is that in useEffect I loop through six items every time when only one thing changes. How to solve it to change only one variable which was changed in reducer function not looping for 6 items when only one was changed, or is it okay to keep code like this?
const initialReducerValue = {
name: {
val: '',
isValid: false,
},
lastName: {
vaL: '',
isValid: false
},
phoneNumber: {
val: '',
isValid: false
},
city: {
val: '',
isValid: false,
},
street: {
val: '',
isValid: false
},
postal: {
val: '',
isValid: false
},
}
const OrderForm = () => {
const orderReducer = (state, action) => {
if (action.type === 'HANDLE TEXT CHANGE') {
return {
...state,
[action.field]: {
val: action.payload,
isValid: true
}
}
}
}
const [formState, formDispatch] = useReducer(orderReducer, initialReducerValue)
const [formIsValid, setFormIsValid] = useState(false)
const changeTextHandler = (e) => {
formDispatch({
type: 'HANDLE TEXT CHANGE',
field: e.target.name,
payload: e.target.value
})
}
useEffect(() => {
const validationArray = []
for (const key of Object.keys(formState)) {
validationArray.push(formState[key].isValid)
}
const isTrue = validationArray.every(item => item)
setFormIsValid(isTrue)
}, [formState])
This code
const validationArray = []
for (const key of Object.keys(formState)) {
validationArray.push(formState[key].isValid)
}
const isTrue = validationArray.every(item => item)
is equivalent to
const isTrue = Object.values(formState).every(item => item.isValid);
This still iterates over all items when only one was changed, but with a temporary array less.
For six items, I would not spend time trying to optimize this code further, but that's your choice.
For my email field, I store and query emails as lowercase strings to avoid duplicate emails like user#example.com and User#example.com. I have a set method defined in my model like:
const User = sequelize.define('user', {
email: {
type: DataTypes.STRING,
unique: { msg: 'That email is already registered.' },
validate: { isEmail: { msg: 'Invalid email.' } },
set(value) {
this.setDataValue('email', value.toLowerCase().trim())
}
}
})
This prevents setting emails with uppercase letters, but it does not prevent queries with uppercase letters. To avoid queries, I have to remember to use .toLowerCase() everywhere. It would be better if I could define it on the model so that a query like this would just work:
const user = await User.findOne({ where: { email: 'SomeEmail#example.com' } })
You can use the hooks in models to store the email in lower case.
Please have a look in below example
const createUserModel = (sequelize, { STRING, UUIDV4, UUID, DATE }) => {
const User = sequelize.define(
'User',
{
userId: {
type: UUID,
defaultValue: UUIDV4,
primaryKey: true,
},
email: {
type: STRING,
allowNull: false,
unique: true,
validate: {
isEmail: true,
},
},
password: {
type: STRING,
allowNull: true,
},
},
{
freezeTableName: true,
timestamps: false,
hooks: {
beforeCreate: async instance => {
const email = instance.get('email');
instance.set('email', email.toLowerCase());
},
beforeUpdate: async instance => {
if (instance.changed('email')) {
const email = instance.get('email');
instance.set('email', email.toLowerCase());
}
},
},
},
);
return User;
};
module.exports = {
createUserModel,
};
Hello i have my reducers like this
case UPDATE_USER: {
return {
...state,
...action.newDataUser,
}
}
My object user is :
{
name: 'azerty',
email: 'azerty#yopmail.com',
birthday: '1990'
}
I have an action to update my user object :
export function updateUser(newDataUser) {
return { type: UPDATE_USER, newDataUser }
}
How to modify my reducers UPDATE_USER to update user object with multiple properties :
{
name: 'azerty updated',
email: 'azerty#yopmail.com updated',
}
Thanks
You can manually update required properties
case UPDATE_USER: {
let user = action.newDataUser;
['name', 'email', 'birthday'].forEach(key => {
user[key] = `${user[key]} updated`;
});
return {
...state,
...user,
}
}
I am using redux for my application's state but I find it hard to update the state correctly when it is nested.
As you can see I use the ...state in my reducer but is there a way to use this when I only need to update a key of a child object and keep the rest of the state ? See below for example
// initial state
state = {
isFetching: true,
isUpdating: false,
content: {
key: 'content',
otherkey: 'content' // Keep this one
}
}
// returned new state
{
...state,
content: {
key: 'thing I only want to update'
}
}
Actions
export function requestUser() {
return {
type: REQUEST_USER
};
}
export function receiveUser(data) {
return {
type: RECEIVE_USER,
payload: data
};
}
export function fetchUser(userhash) {
return function (dispatch) {
dispatch(requestUser);
return new Promise(resolve => setTimeout(resolve, 500)).then(() => {
const data = {
status: 200,
data: {
firstName: 'Neal',
lastName: 'Van der Valk',
email: 'email#outlook.com',
hash: 'zea7744e47747851',
permissions: {
'admin': true,
'results': true,
'database': true,
'download': true,
'property': true,
'departments': true,
'users': true,
'devices': true,
'integrations': true,
},
notifications: {
'daily': true,
'weekly': false
}
}
};
dispatch(receiveUser(data));
});
};
}
Reducer
const INITIAL_STATE = {
isFetching: true,
isUpdating: false,
content: null
};
export default function(state = INITIAL_STATE, action) {
switch (action.type) {
case REQUEST_USER:
return {
...state,
isFetching: true
};
case RECEIVE_USER:
return {
...state,
isFetching: false,
content: action.payload.data
};
You can try Object.assign()
This example shows the usage.
{
...state,
content: Object.assign({}, state.content, {
key: 'thing I only want to update'
}
}
You can also use the same spread operator ...
var state = {
isFetching: true,
isUpdating: false,
content: {
key: 'content',
otherkey: 'content' // Keep this one
}
};
var newState = {
...state,
content: {
...state.content,
key: 'thing I only want to update'
}
}
console.log(newState);
In your initial state, content should be {} instead of null.
Then you can change the state in your reducer with Object.assign.
example :
case RECEIVE_USER:
return{
...state,
content: Object.assign({}, state.content, {
key: 'thing I only want to update'
}