Not able to add data using mutation on Apollo Client

Viewed 57

Mutation on client side of Apollo server:

import { gql } from "@apollo/client";
export const UPLOAD_IMAGE = gql`
  mutation uploadImage($url: String!, $description: String!, $posterName: String!) {
    uploadImage(post: { url: $url, description: $description , posterName: $posterName }) {
      
      
      url
      posterName
      description
      
    
    }
  }
`;

Trying to add new post:

import { useMutation, useQuery } from "@apollo/client";
import { UPLOAD_IMAGE } from "./mutation";
import { useState } from "react";
function NewPost() {
  
  const [posterName, setPosterName] = useState(null);
  const [uu, {err}] = useMutation(UPLOAD_IMAGE);
  const [url, setUrl] = useState(null);
  const [description, setDescription] = useState(null);
  
  
  const addPost = () => {
    uu({
      variables: {
        url: url,
        description: description,
        posterName: posterName,
        
      },
    });
  };

  return (
    <div className="App">
     
      Url--- <input onChange={(e) => setUrl(e.target.value)} />
      <br />
      PosterName--- <input onChange={(e) => setPosterName(e.target.value)} />
      <br />
      Description ---
      <input onChange={(e) => setDescription(e.target.value)} />
      <br />
      <button onClick={() => addPost()}>Add Post</button>
    </div>
  );
}

export default NewPost;

Mutation on Server side, Apollo server:

Typedef:

type Mutation {
    uploadImage(
      url: String
      description: String
      posterName: String
    ): ImagePost
  }

Resolver:

Mutation: {
      uploadImage: async (_,args) => {
        //const { data } = await axios.get('https://api.unsplash.com/photos/?client_id=2zceQd7D4SraKoqW_GjPzXboSup3TKRIPk7EXfJBcAs');
        const newPost = {
          id: uuid.v4(),
          url: args.url,
          description: args.description,
          posterName: args.posterName,
          binned: false,
          userPosted: true,

        }
        await client.lpushAsync("postedImagesList",JSON.stringify(newPost));
        return newPost;
      }
    }

When a new post is created I am adding it to Redis to store it. But the post does not get added from the input fields and button. It does work using the playground, not sure why. I am retrieving the data using lrangeasync to get back data from Redis.

1 Answers

Try this!

const addPost = async () => {
  await uu({
    variables: {
      post: {
        url: url,
        description: description,
        posterName: posterName,
      },
    },
  });
};
Related