1

I can add a Task on my site, but I cannot see it until I reload the page. That means I have the data on my database and I can see it on Apollo4.

I need to update the cache manually. I've been able to update updateTaskDone and deleteTask but newTask is not working.

Thank you in advance.

Full code here:

import './App.css';
import Task from './Task';
import React from 'react';
import TaskForm from './TaskForm';
import { useEffect, useState } from "react";
import {useQuery,gql,useMutation,useApolloClient} from '@apollo/client'

const GET_TASKS = gql`
  query tasks {
    tasks {
      name
      done
      id
    }
  }
`;

const ADD_TASK = gql`
mutation newTask($input: taskInput!) {
  newTask(input: $input) {
    name
  }
}
`;

const TASK_DONE = gql`
  mutation updatedTask($id: ID!) {
    updatedTask(id: $id) 
  }
`;

const DELETE_TASK = gql`
  mutation deletedTask($id: ID!) {
    deletedTask(id: $id) 
  }
`;

const UPDATE_TITLE = gql`
mutation newupdatedTitleTask( $id: ID! $input: titleInput!) {
  updatedTitle(id: $id, input: $input)
}
`;

function App() {

  const { data: tasksData } = useQuery(GET_TASKS)
  const [updateTitleMutation] = useMutation(UPDATE_TITLE)
  const [addTaskMutation] = useMutation(ADD_TASK)
  const [deletedTaskMutation] = useMutation(DELETE_TASK)
  const [updateTaskDoneMutation] = useMutation(TASK_DONE)
  const tasks = tasksData?.tasks ?? [];
 
  useEffect(() => {
    localStorage.setItem('tasks', JSON.stringify(tasks));
  }, [tasks]);

  function AddTask(name) {
    addTaskMutation({
      variables: {
        input: {
          name: name
        }
      },
      update: (cache, { data: { newTask } }) => {
        const { tasks } = cache.readQuery({ query: GET_TASKS });
        const updatedTasks = [...tasks, newTask];
        cache.writeQuery({
          query: GET_TASKS,
          data: { tasks: updatedTasks }
        });
      }
    });
  }
  
  
  function removeTask(index) {
    const taskId = tasksData.tasks[index].id;
    deletedTaskMutation({
      variables: {
        id: taskId
      },
      update: (cache) => {
        const existingTasks = cache.readQuery({ query: GET_TASKS });
        const updatedTasks = existingTasks.tasks.filter((task, i) => i !== index);
        cache.writeQuery({
          query: GET_TASKS,
          data: { tasks: updatedTasks }
        });
      }
    });
  }
  
  function updateTaskDone(index, done) {
    const taskId = tasksData.tasks[index].id;
    updateTaskDoneMutation({
      variables: {
        id: taskId,
        done: done
      },
      update: (cache) => {
        const existingTasks = cache.readQuery({ query: GET_TASKS });
        const updatedTasks = existingTasks.tasks.map((task, i) => {
          if (i === index) {
            return { ...task, done };
          }
          return task;
        });
        cache.writeQuery({
          query: GET_TASKS,
          data: { tasks: updatedTasks }
        });
      }
    });
  }

  function renameTasks(index, newName) {
    const taskId = tasksData.tasks[index].id;
    updateTitleMutation({
      variables: {
        id: taskId,
        input: {
          name: newName
        }
      }
    });
  }
  
  function getMessage() {
    const percentage = numberTotal === 0 ? 0 : (numberComplete / numberTotal) * 100;
    if (percentage === 0) {
      return 'no tasks complete ';
    }
    if (percentage === 100) {
      return 'nice job! ';
    }
    return 'keep it up! ';
  }
  
  const numberComplete = tasks.filter(t => t.done).length;
  const numberTotal = tasks.length;

//{tasksData && tasksData.tasks && tasksData.tasks.map((task, index) => (
  return (
    <main>
      <h1>{numberComplete}/{numberTotal} Complete</h1>
      <h2>{getMessage()}</h2>
      <TaskForm onAdd={AddTask} />
      {tasks.map((task, index) => (
        <Task
          {...task}
          key={index}
          onRename={newName => renameTasks(index, newName)}
          onTrash={() => removeTask(index)}
          onToggle={done => updateTaskDone(index, done)}
        />
      ))}
    </main>
  );

}

export default App;

isherwood
  • 58,414
  • 16
  • 114
  • 157
anfield
  • 31
  • 6

1 Answers1

0

You must subscribe to query to receive updates

const chatId = '123456';

const querySubscription = client.watchQuery({
  query: GET_CHAT_MESSAGES,
  variables: {
    chatId,
  },
  fetchPolicy: 'cache-and-network'
}).subscribe({
  next: ({ data }) => { // do stuff },
  error: (e) => console.error(e)
})

After that, when you update your Apollo cache, it will reflect the changes in your component

Medet Tleukabiluly
  • 11,662
  • 3
  • 34
  • 69