I get todo list with useQuery.
const { data, refetch } = useQuery(GET_TODOS);
After creating a todo, I get todo list with refetch like below.
const [ addTodo ] = useMutation(ADD_TODO, {
onComplete: () => refetch()
});
const handleAddTodo = useCallback((todoArgs) => {
addTodo({ variables: todoArgs });
}, []);
But It is obviously wasted time.
I tried to update only in an updated part. for that, I saved todos into a state and I changed this.
const [todos, setTodos] = useState([]);
...
const [ addTodo ] = useMutation(ADD_TODO, {
onComplete: (updatedData) => {
setTodos((prevTodos) => {
const newTodos = prevTodos.map((todo) => todo.id === updatedData.id ? updatedData : todo);
return newTodos;
});
}
}
...
useEffect(() => {
setTodos(data);
}, [data]);
...
But I'm not sure It is a right way. I think there may be an official way for updating a part of data.
What's the best way to fetch a partial data after Creating, Updating, Deleting?
I'm using 'no-cache' as a default option in the project.
Managing the query response in a new state seems a bit overkill to me.
In fact, Apollo GraphQL client automatically refetch the updated data, as long as you are returning the updated data id field in the mutation result.
For other cases, you may want to use a custom update function option.
You can read more about that here:
https://www.apollographql.com/blog/apollo-client/caching/when-to-use-refetch-queries/