Skip to content

Commit

Permalink
feat: reset todos order values on reload (#9)
Browse files Browse the repository at this point in the history
  • Loading branch information
tobiasprima authored Mar 21, 2024
1 parent 1f40e43 commit ab71ab4
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 2 deletions.
12 changes: 11 additions & 1 deletion src/app/api/apiSlice.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ export const apiSlice = createApi({
endpoints: (builder) => ({
getTodos: builder.query({
query: () => '/todos',
transformResponse: res => res.sort((a,b) => b.order - a.order),
providesTags: ['Todos']
}),
addTodo: builder.mutation({
Expand Down Expand Up @@ -49,6 +50,14 @@ export const apiSlice = createApi({
body: todos
}),
invalidatesTags: ['Todos']
}),
resetTodo: builder.mutation({
query: (todos) => ({
url: '/todos/reset',
method: 'POST',
body: todos
}),
invalidatesTags: ['Todos']
})
})
})
Expand All @@ -59,5 +68,6 @@ export const {
useUpdateTodoMutation,
useDoneTodoMutation,
useDeleteTodoMutation,
useReorderTodoMutation
useReorderTodoMutation,
useResetTodoMutation
} = apiSlice
14 changes: 13 additions & 1 deletion src/features/todos/TodoList.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,12 +8,14 @@ import {
useDoneTodoMutation,
useDeleteTodoMutation,
useReorderTodoMutation,
useResetTodoMutation,
} from '../../app/api/apiSlice'

const TodoList = () => {
const [ isResetDone, setisResetDone ] = useState(false);
const [ todoWithoutDB, setTodoWithoutDB ] = useState([])
const [ newTodo, setNewTodo ] = useState('')
const [moveDoneToEnd, setMoveDoneToEnd] = useState(false);
const [ moveDoneToEnd, setMoveDoneToEnd ] = useState(false);

const {
data: todos,
Expand All @@ -26,6 +28,7 @@ const TodoList = () => {
const [ doneTodo ] = useDoneTodoMutation()
const [ deleteTodo ] = useDeleteTodoMutation()
const [ reorderTodo ] = useReorderTodoMutation()
const [ resetTodo ] = useResetTodoMutation()

// Effect to load todos from local storage if there is cache
useEffect(() => {
Expand All @@ -39,6 +42,15 @@ const TodoList = () => {
}
}, [todos])

// Reset Order to 0 when page first mounted
useEffect(()=> {
if (todos && !isResetDone){
resetTodo(todos)
setisResetDone(true)
}
}, [todos, isResetDone, resetTodo])


// Effect to save todos to local storage when todos change
useEffect(() => {
localStorage.setItem('todos', JSON.stringify(todoWithoutDB))
Expand Down
2 changes: 2 additions & 0 deletions src/index.css
Original file line number Diff line number Diff line change
Expand Up @@ -181,6 +181,8 @@ input[type="text"] {

.content{
margin-bottom: 2rem;
max-height: 600px;
overflow-y: auto;
}

.submit:hover .svg-inline--fa {
Expand Down

0 comments on commit ab71ab4

Please sign in to comment.