Skip to content

Instantly share code, notes, and snippets.

@oshimayoan
Created September 28, 2020 06:55
Show Gist options
  • Select an option

  • Save oshimayoan/c0cfc974c1cba8f4a9154fba19eb5af1 to your computer and use it in GitHub Desktop.

Select an option

Save oshimayoan/c0cfc974c1cba8f4a9154fba19eb5af1 to your computer and use it in GitHub Desktop.
Generated by XState Viz: https://xstate.js.org/viz
// Tallio saved post library
function toggle(action) {
return assign({
posts: (context) => {
let index = context.posts.findIndex((post) => post.id === '1');
let updatedPost = {
...context.posts[index],
saved: action === 'save',
};
console.log('index',index)
return [
...context.posts.slice(0, index),
updatedPost,
...context.posts.slice(index + 1),
]
}
})
}
const savedPostMachine = Machine({
id: 'savedPost',
initial: 'idle',
context: {
posts: [
{
id: '1',
saved: false
}
]
},
states: {
idle: {
on: {
TOGGLE: 'toggling',
}
},
toggling: {
on: {
SAVE: {
target: 'saving',
cond: (context) => !context.posts[0].saved
},
REMOVE: {
target: 'confirmRemove',
cond: (context) => context.posts[0].saved
}
}
},
saving: {
on: {
FAIL: 'idle',
SUCCESS: {
target: 'idle',
actions: toggle('save')
},
}
},
removing: {
on: {
FAIL: 'idle',
SUCCESS: {
target: 'idle',
actions: toggle('remove')
},
}
},
confirmRemove: {
on: {
NO: 'idle',
YES: 'removing',
}
},
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment