how to update filtered data with RTK Query createSelector

Viewed 14

I want to update todos with filtered data I created with createSelector. How to approach this situation to update effectively when new todo is added or deleted within component?

import { createSelector } from "@reduxjs/toolkit";

import {
  useGetTodosQuery,
} from "../api/apiSlice";

export default function TodoList(){

// RTK Query filters
  const selectCompletedPosts = useMemo(() => {
    const emptyArray = [];
    // Return a unique selector instance for this page so that
    // the filtered results are correctly memoized
    return createSelector(
      (inputData) => inputData,
      (data) =>
        data?.data?.filter((todo) => todo.isCompleted === true) ?? emptyArray
    );
  }, []);


// Queries and Mutations
const {
    data: todos,
    completedTodos,
    isLoading,
    isSuccess,
    isError,
    error,
  } = useGetTodosQuery(undefined, {
    selectFromResult: (result) => ({
      // We can optionally include the other metadata fields from the result here
      ...result,
      // Include a field called `filteredData` in the result object,
      // and memoize the calculation
      completedTodos: selectCompletedPosts(result)
    }),
});

const [deleteTodo, { isLoading: isDeleting }] = useDeleteTodoMutation();


let content;
if (isLoading) {
  content = <div>loading..</div>;
} else if (isSuccess) {
  content =
    todos.length > 0 ? (
      <div>
        {todos.map((todo) => {
          return <div>{todo.content} <span onClick={()=>deleteTodo({ id: todo.id })}></span></div>;
        })}
      </div>
    ) : (
      <p>
        No todos, yet.
      </p>
    );
} else if (isError) {
  content = <p>{error}</p>;
}


return (
  <div>{content}</div>
)

}

0 Answers
Related