How to make a graphql entry in a psql database - graphql

I am trying to figure out how to make a graphql entry in a psql database.
I am stuck and am not getting any feedback from console logs at any point in my attempt. I'm stuck for what to try next (or where to look for a tutorial showing how this step is supposed to work).
I have a table in my prisma schema called 'issue'. I am trying to create an 'issue' entry.
I have made a form with:
import * as React from "react"
import { Box, Center, Heading, Button, } from "#chakra-ui/react"
import { Select, OptionBase, GroupBase } from "chakra-react-select";
import { groupedIssueCategories } from "../components/issue/categories"
import { gql } from "#apollo/client"
import Head from 'next/head'
import { IssueInput, useAllIssuesQuery, useCreateIssueMutation } from "lib/graphql"
import * as c from "#chakra-ui/react"
import { Input } from "components/Input"
// import { Select } from "components/Select"
import { HomeLayout } from "components/HomeLayout"
import { Limiter } from "components/Limiter"
import { Form } from "components/Form"
import Yup from "lib/yup"
import { useForm } from "lib/hooks/useForm"
import { useMe } from "lib/hooks/useMe"
import { useToast } from "lib/hooks/useToast"
interface GroupedRiskOption extends OptionBase {
label: string
value: string
}
const _ = gql`
mutation CreateIssue($data: IssueInput!) {
createIssue(data: $data) {
id
title
issueCategory
description
userId
}
}
query AllIssues {
allIssues {
id
title
issueId
description
userId
}
}
`
export default function Issue() {
const toast = useToast()
const { me, loading: meLoading } = useMe()
const [createIssue] = useCreateIssueMutation()
const { data: issues, refetch } = useAllIssuesQuery()
const IssueSchema = Yup.object().shape({
title: Yup.string().required("Title is required"),
issueCategory: Yup.string().required("Category is required"),
description: Yup.string().required("Description is required"),
})
const form = useForm({ schema: IssueSchema })
const onSubmit = (data: IssueInput) => {
console.log(data)
return form.handler(() => createIssue({ variables: { data: { ...data, userId: me?.id || ""} } }), {
onSuccess: async () => {
toast({
title: "Issue created",
description: "Your issue has been created",
status: "success",
})
refetch()
form.reset()
},
})
}
if (meLoading)
return (
<c.Center>
<c.Spinner />
</c.Center>
)
if (!me) return null
return (
<Box>
<Head>
<title>Create Issue</title>
</Head>
<Limiter pt={20} minH="calc(100vh - 65px)">
<Center flexDir="column">
<Heading as="h1" size="3xl" fontWeight="extrabold" px="3rem" lineHeight="1.2" letterSpacing="tight" color="brand.orange">
Create Issue
</Heading>
<Form onSubmit={onSubmit} {...form}>
<c.Stack spacing={2}>
<c.Heading>Issues</c.Heading>
<Input autoFocus name="title" label="Title" placeholder="Eg: climate change" />
<Input name="description" label="Description" placeholder="Eg: Issues relating to climate change" />
<Select<GroupedRiskOption, true, GroupBase<GroupedRiskOption>>
// isMulti
name="issueCategory"
options={groupedIssueCategories}
placeholder="Select issue categories"
closeMenuOnSelect={false}
/>
<Button
color="brand.orange"
type="submit"
isFullWidth
isDisabled={form.formState.isSubmitting ||
!form.formState.isDirty}
isLoading={form.formState.isSubmitting}
>
Create Issue
</Button>
<c.List>
{/* {issues.allIssues.map((issue) => (
<c.ListItem key={issue.id}>
{issue.title}
{issue.issueCategory}
{issue.description}
</c.ListItem>
))} */}
</c.List>
</c.Stack>
</Form>
</Center>
</Limiter>
</Box>
)
}
Issue.getLayout = (page: React.ReactNode) => <HomeLayout>{page}</HomeLayout>
I have a create issue mutation in my lib/graphql:
export function useCreateIssueMutation(baseOptions?: Apollo.MutationHookOptions<CreateIssueMutation, CreateIssueMutationVariables>) {
const options = {...defaultOptions, ...baseOptions}
return Apollo.useMutation<CreateIssueMutation, CreateIssueMutationVariables>(CreateIssueDocument, options);
}
export type CreateIssueMutationHookResult = ReturnType<typeof useCreateIssueMutation>;
export type CreateIssueMutationResult = Apollo.MutationResult<CreateIssueMutation>;
export type CreateIssueMutationOptions = Apollo.BaseMutationOptions<CreateIssueMutation, CreateIssueMutationVariables>;
When I click submit, nothing happens in the console. I can't log the data, and I can't see any errors, either in the terminal or in the console.
Can anyone give me a steer on where to look for insights as to what is going wrong. There is no data in the database, the onSuccess step doesn't get performed.

Related

Why are the components not rerendering after Response?

Table with pinia store equipmentlist, fethced from usequipments but table does not rerender
VueTableComponent
<script setup lang="ts">
import { useEquipmentStore } from '~/store/equipmentStore'
import useEquipments from '~/composables/equipments'
const { getEquipmentList } = useEquipments()
onBeforeMount(() => { getEquipmentList() })
const state = useEquipmentStore()
const equipmentList: any = state.equipmentList
const loaded = state.loaded
</script>
<template>
<el-table :key="loaded" :data="equipmentList" style="width: 100%">
<el-table-column type="expand">
<template #default="props">
ID: {{ props.row.id }}
</template>
</el-table-column>
<el-table-column label="ID" prop="id" />
<el-table-column label="Name" prop="name" />
</el-table>
</template>
Typescript File for all CRUD Operations equipment.ts
import { useRouter } from 'vue-router'
import http from '../http-common'
import { useEquipmentStore } from '~/store/equipmentStore'
export default function useEquipments() {
const state = useEquipmentStore()
const errors = ref([]) // array of strings
const router = useRouter()
const getEquipmentList = async() => {
try {
console.log(state.equipmentList.length)
const response = await http.get('/equipment/list')
state.equipmentList = response.data
console.log(state.equipmentList.length)
console.log(state.equipmentList[0])
}
catch (error: any) {
console.log(error.message)
}
}
Equipment(Pinia)Store
import { defineStore } from 'pinia'
import type { Ref } from 'vue'
export const useEquipmentStore = defineStore('equipment', {
state: () => ({
equipment: ref({}) as any,
equipmentList: ref([]) as Ref<any[]>,
}),
actions: {
reset() {
this.equipment = {}
this.equipmentList = []
},
},
})
1. i called several times getEquipment list and it is faster done then i stored an initial equipment, 2. i clicked on the link on the left and fetched several times more and as u can see there is something fetchd but not displayed, 3. after repeating to home and again to Link the component is there and alll other next fetches do indeed function well
Main.ts
app.component('InputText', InputText)
app.mount('#app')
useEquipments().initDB()
}
same fetching class equipment.ts
const initDB = () => {
try {
if (state.equipmentList.length === 0) { storeEquipment({ id: 1, name: 'Firma' }) }
else {
for (const equipment of state.equipmentList) {
console.log(equipment)
if (equipment === 'Firma')
state.equipmentList.splice(state.equipmentList.indexOf(equipment), 1)
}
}
}
catch (error: any) {
console.log(error.message)
}
}

Apollo GraphQL pass object

In GraphQL, how do I pass an object instead of a string?
Take this code from Apollo's website as an example, with my minor change:
import React, { useState } from 'react';
import { useLazyQuery } from '#apollo/client';
function DelayedQuery() {
const [dog, setDog] = useState(null);
const [getDog, { loading, data }] = useLazyQuery(GET_DOG_PHOTO);
if (loading) return <p>Loading ...</p>;
if (data && data.dog) {
setDog(data.dog);
}
const myObject = {
type: {
favors: [
tom: true,
bill: false
]
}
}
return (
<div>
{dog && <img src={dog.displayImage} />}
<button onClick={() => getDog({ variables: { theObject: myObject } })}>
Click me!
</button>
</div>
);
}
I believe React is trying to parse the object into a string, but (as the error message explains) JSON.stringify cannot serialize cyclic structures.
What do I do?

Using Form.Select from React Semantic UI with React-hooks

as the question suggests, I'm using RSUI with React-Hooks in a Next.js project and I'm trying to figure out how to send a payload from a Form.Select to a graphql endpoint. I've included a lot of extra code for context but really what I'm after is to successfully set "security_type" using setValues
import React, { useState } from 'react'
import Router from 'next/router'
import { Button, Checkbox, Form, Segment, Table } from 'semantic-ui-react'
import Layout from '../../components/layout'
import Loading from '../../components/loading'
import Error from '../../components/error'
import { useFetchUser } from '../../lib/user'
import { useQuery, useMutation } from '#apollo/react-hooks';
import query from '../../graphql/project/query';
import mutation from '../../graphql/project/mutation';
const security_types = [
{ key: 'Bank Guarantee', value: 'Bank Guarantee', text: 'Bank Guarantee', name: 'Bank Guarantee' },
{ key: 'Cash Retention', value: 'Cash Retention', text: 'Cash Retention', name: 'Cash Retention' },
{ key: 'Surety Bond', value: 'Surety Bond', text: 'Surety Bond', name: 'Surety Bond' },
];
function CreateProject() {
const { loading, error, data } = useQuery(query);
const [createProject] = useMutation(mutation,
{
onCompleted(data) {
Router.replace("/create_project", "/project/" + data.createProject.project_id, { shallow: true });
}
});
const { user, user_loading } = useFetchUser()
let [form, setValues] = useState({
project_number: '',
project_name: '',
security_type: '',
});
let updateField = e => {
console.log('e: ', e)
setValues({
...form,
[e.target.name]: e.target.value
});
};
let mutationData = ''
if (loading) return <Loading />;
if (error) return <Error />;
return (
<Layout user={user} user_loading={user_loading}>
<h1>Let's create a project</h1>
{user_loading ? <>Loading...</> :
<div>
<Segment>
<Form
onSubmit={e => {
e.preventDefault();
console.log('form: ', form)
createProject({ variables: { ...form } });
form = '';
}}>
<Form.Input
fluid
label='Project Number'
name="project_number"
value={form.project_number}
placeholder="Project Number"
onChange={updateField}
/>
<Form.Input
fluid
label='Project Name'
name="project_name"
value={form.project_name}
onChange={updateField}
/>
<Form.Select
fluid
selection
label='Security Type'
options={security_types}
placeholder='Security Type'
name="security_type"
value={form.security_type}
onChange={(e, { value }) => setValues(console.log('value: ', value), { "security_type": value })}
/>
<Button>Submit</Button>
</Form>
</Segment>
</div>
}
</Layout>
);
}
export default CreateProject;
I think all my troubles relate to the onChange section so any help would be great.

I keep getting errors when getting image with gatsby-image and graphql

I am trying to add an image sourced from graphql. I've run into this problem a few times now and always end up lucking out into a fix.
When querying the image I get this response:
The "path" argument must be one of type string, Buffer, or URL.
Received type undefined
The code is as follows:
import React from 'react'
import { Link, graphql, useStaticQuery, StaticQuery } from 'gatsby'
import Img from 'gatsby-image'
import './longCard.css';
const CardData = props => {
const slug = props.slug;
return (
<StaticQuery
query={
graphql`
query($slug: String) {
sanityProduct(slug: {current: {eq: $slug}}) {
slug{
current
}
title
featured_image {
asset {
childImageSharp {
fixed {
...GatsbyImageSharpFixed
}
}
}
}
}
}
`}
render={data => <LongCard />}
/>
)
}
export default CardData
export const LongCard = ({ data }) => {
return (
<div className="long-card">
<div className="long-card-inner">
<Link to={data.sanityProduct.slug.current}>{data.sanityProduct.title}</Link>
{/* Add image */}
<Img fixed={data.featured_image.asset.childImageSharp.fixed} />
</div>
</div>
)
}
I didn't need the ChildImageSharp section, I think this is only for querying the file-system.

relay refetch doesn't show the result

I'm trying to create a live search-result component(lazy load one). It works perfectly for the first time but refetch doesn't update the data. I see the request and respoonse in Network tab! so it does get the data, but it doesn't supply it to the component!
any idea why?
import React, { Component } from 'react';
import {
createRefetchContainer,
graphql,
} from 'react-relay';
import ProfileShow from './ProfileShow';
class ProfileList extends Component {
render() {
console.log("rendering....", this.props)
return (
<div className="row">
<input type="text" onClick={this._loadMe.bind(this)} />
{this.props.persons.map((person) => {
return (
<div className="col-md-3">
<ProfileShow person={person} />
</div>
);
})}
</div>
);
}
_loadMe(e) {
const refetchVariables = fragmentVariables => ({
queryStr: e.target.value,
});
this.props.relay.refetch(refetchVariables, null, (...data) => {
console.log(data)
});
}
}
const FragmentContainer = createRefetchContainer(
ProfileList,
{
persons: graphql.experimental`
fragment ProfileList_persons on Person #relay(plural: true) {
fullname
number
email
pic
}
`
},
graphql.experimental`
query ProfileListRefetchQuery($queryStr: String!) {
talentList(query: $queryStr) {
...ProfileList_persons
}
}
`,
);
export default FragmentContainer;

Resources