How to transform received data from @apollo/react-hooks

Viewed 1637

I am using `` query:

const GET_COMMENTS = gql`
    query getComments {
        getComments (where: {code: "/about-us" }) {
            id
            text
            createdAt
        }
    }
`
....
const { loading, error, data } = useQuery(GET_COMMENTS);

in my code...

The code is fetching comments from the server in comment object is a date: string! property, I would like to transform this date: string! into javascript date (new Date(comment.date)) how can I do it directly after data fetch?

I don't want to transform every render is called.

Is there any something like this?:

const { loading, error, data } = 
   useQuery(
      GET_COMMENTS, 
      {
         transform: (data) => data.map(comment => ({...comment , date: new Date(comment.date)}) )
      }
   );

Thank you for your help!

3 Answers

The merge function in cache type policies is what you are looking for. It allows you to define a custom strategy for writing incoming data into the cache.

When creating the cache you can define how to write specific fields. Let's assume the date field belongs to the Comment type:

const cache = new InMemoryCache({
  typePolicies: {
    Comment: {
      fields: {
        date: {
          merge(_, date) {
            return new Date(date);
          },
        },
      },
    },
  },
});

You can call your transformer function inside onCompleted and use its result as a state variable.

const [myData, setMyData] = useState([]);
const { loading } = useQuery(GET_DATA_QUERY, {
  variables: {
    options: {
      limit: 20
    }
  },
  onCompleted: (response) => {
    const transformed = tranformData(response)
    setMyData(transformed)
  }
});

return (
  <div style={{ color: "white" }}>
    {loading ? <div>Loading..</div> : <div>{myData.length}</div>}
  </div>
);
Related