Skip to content

Instantly share code, notes, and snippets.

@dineshigdd
Created June 11, 2023 16:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dineshigdd/4e7cf091c4b7b47d29447597c9b34f5d to your computer and use it in GitHub Desktop.
Save dineshigdd/4e7cf091c4b7b47d29447597c9b34f5d to your computer and use it in GitHub Desktop.
This is the component for creating a post. It uses GraphQL mutation.
import React , { useEffect, useRef, useState } from 'react';
import { useMutation } from '@apollo/client';
import { CREATE_POST } from './mutations'
export default function CreatePost() {
const titleRef = useRef();
const bodyRef = useRef();
const [ state, setState ] = useState('')
const [addPost, { data, loading, error }] = useMutation( CREATE_POST );
useEffect(()=>{
if( data ) {
let { id, title , body } = data.createPost;
setState( `${ id } ${ title } ${ body }` );
}
},[ data ]);
if (loading) return 'Submitting...';
if (error) return `Submission error! ${error.message}`;
return (
<div>
<form
onSubmit={e => {
e.preventDefault();
addPost({
variables: {
input: {
title: titleRef.current.value ,
body: bodyRef.current.value }
}});
titleRef.current.value = '';
bodyRef.current.value = '';
}}
>
<input ref={ titleRef } />
<input ref={ bodyRef } />
<button type="submit">Add Post</button>
</form>
{ state }
</div>
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment