Skip to content

Instantly share code, notes, and snippets.

@dbasilioesp
Last active September 25, 2020 13:35
Show Gist options
  • Save dbasilioesp/eb968e9c9a9013dc4d39ceaaad3201d4 to your computer and use it in GitHub Desktop.
Save dbasilioesp/eb968e9c9a9013dc4d39ceaaad3201d4 to your computer and use it in GitHub Desktop.
Network Redux
const NAME = "network";
const types = {
NAME,
SET: `${NAME}/SET`,
RESET: `${NAME}/RESET`,
CREATE: `${NAME}/CREATE`,
UPDATE: `${NAME}/UPDATE`,
DELETE: `${NAME}/DELETE`
};
/*
const SCHEMA = {
domain: { type: String },
isFetching: { type: Boolean },
status: { type: String },
error: { type: Object }
}
*/
const INITIAL_STATE = {
collection: []
};
export default {
types,
actions: {
set(collection) {
return { type: types.SET, payload: { collection } };
},
create({ domain }) {
let payload = { domain };
return { type: types.CREATE, payload };
},
update({ domain, status, error }) {
let payload = { domain, status, error };
return { type: types.UPDATE, payload };
},
delete({ domain }) {
let payload = { domain };
return { type: types.DELETE, payload };
},
reset() {
return { type: types.RESET };
}
},
reducers(state = INITIAL_STATE, action) {
switch (action.type) {
case types.SET: {
const { collection } = action.payload;
return { ...state, collection };
}
case types.CREATE: {
const { domain } = action.payload;
const network = {
domain,
isFetching: true,
status: null,
error: null
};
const collection = [...state.collection, network];
return { ...state, collection };
}
case types.UPDATE: {
const { domain, status, error } = action.payload;
let collection = state.collection.map(item => {
if (item.isFetching === true && item.domain === domain) {
return { ...item, isFetching: false, status, error };
} else {
return item;
}
});
return { ...state, collection };
}
case types.DELETE: {
const { domain } = action.payload;
let collection = state.collection.filter(i => i.domain !== domain);
return { ...state, collection };
}
case types.RESET: {
return { ...INITIAL_STATE };
}
default:
return state;
}
},
selectors: {
getLastOfDomain(state, domain) {
let collection = state[NAME].collection;
collection = [...collection];
collection.reverse();
return collection.find(i => i.domain === domain);
}
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment