Reactjs 下一个JS apollo链接更改清除查询,必须刷新页面才能运行查询

Reactjs 下一个JS apollo链接更改清除查询,必须刷新页面才能运行查询,reactjs,graphql,next.js,apollo,Reactjs,Graphql,Next.js,Apollo,我将Next JS与Apollo一起使用,下面的查询运行得很好,但是当我从页面导航到另一个页面并返回时,查询没有运行,我的字段是空的,我必须点击刷新来填充它们。有人知道为什么会这样吗 import { useQuery, gql, useMutation } from "@apollo/client"; import { useEffect, useState } from "react"; import { v4 as uuidv4 } from &qu

我将Next JS与Apollo一起使用,下面的查询运行得很好,但是当我从页面导航到另一个页面并返回时,查询没有运行,我的字段是空的,我必须点击刷新来填充它们。有人知道为什么会这样吗

import { useQuery, gql, useMutation } from "@apollo/client";
import { useEffect, useState } from "react";
import { v4 as uuidv4 } from "uuid";
import Form from "../components/Form";
import Layout from "../components/Layout";

export const INPUT_VALUES = gql`
  query GetInputValues {
    allFormInputVals {
      data {
        name
        _id
        type
        index
      }
    }
  }
`;

const FormBuilder = () => {
  const blankFormInput = {
    __typename: "FormInputVal",
    name: "test",
    _id: uuidv4(),
    type: "text",
  };
  const [formState, setFormState] = useState([blankFormInput]);

  const { loading, error, data } = useQuery(INPUT_VALUES);

  useEffect(() => {
    const formData = data?.allFormInputVals?.data;
    setFormState(formData);
  }, [data]);

  if (loading) return <p>Loading...</p>;

  if (error) return <p>Error: {error.message}</p>;

  return (
    <Layout>
      {formState && <Form formState={formState} setFormState={setFormState} />}
    </Layout>
  );
};

export default FormBuilder;
从“@apollo/client”导入{useQuery,gql,useMutation};
从“react”导入{useffect,useState};
从“uuid”导入{v4 as uuidv4};
从“./组件/表格”导入表格;
从“./组件/布局”导入布局;
导出常量输入值=gql`
查询GetInputValues{
所有形式的输入{
资料{
名称
_身份证
类型
指数
}
}
}
`;
const FormBuilder=()=>{
常量blankFormInput={
__typename:“FormInputVal”,
名称:“测试”,
_id:uuidv4(),
键入:“文本”,
};
常量[formState,setFormState]=使用状态([blankFormInput]);
const{loading,error,data}=useQuery(输入值);
useffect(()=>{
const formData=数据?.allFormInputVals?.data;
setFormState(formData);
},[数据];
如果(加载)返回加载…

; if(error)返回错误:{error.message}

; 返回( {formState&&} ); }; 导出默认FormBuilder;
更新:根据要求,这里是表单componenet

import { useEffect, useState } from "react";
import { useForm } from "react-hook-form";
import { useQuery, gql, useMutation } from "@apollo/client";
import { v4 as uuidv4 } from "uuid";
import styled from "styled-components";
import { INPUT_VALUES } from "../pages/formBuilder";
import Link from "next/link";
import useSWR from "swr";

const ADD_INPUT_VALUES = gql`
  mutation AddInputValues($name: String!, $type: String!, $index: Int!) {
    createFormInputVal(data: { name: $name, index: $index, type: $type }) {
      name
      type
      index
      _id
    }
  }
`;

const UPDATE_FORM_INPUT_VAL = gql`
  mutation UpdateFormInputVal(
    $name: String!
    $type: String!
    $index: Int!
    $ID: ID!
    $arrayOrder: Int
  ) {
    updateFormInputVal(
      id: $ID
      data: { name: $name, type: $type, index: $index, arrayOrder: $arrayOrder }
    ) {
      name
      type
      index
      arrayOrder
    }
  }
`;

const DELETE_FORM_INPUT_VAL = gql`
  mutation DeleteFormInputVal($ID: ID!) {
    deleteFormInputVal(id: $ID) {
      name
    }
  }
`;

const FormStyles = styled.form`
  display: grid;
  grid-template-columns: 350px 1fr 1fr;
  label {
    //background: red;
  }
  input,
  select {
    //background: aqua;
    border: 1px solid grey;
    border-top: 0;
    border-right: 0;
    border-left: 0;
  }
  input[type="button"] {
    background: green;
    border: none;
    border-radius: 30px;
    color: #fff;
    padding: 15px;
    width: 200px;
    margin: 0 0 25px auto;
    &:hover {
      cursor: pointer;
    }
  }
  button {
    background: lightgray;
    padding: 15px;
    border: none;
    &:hover {
      cursor: pointer;
    }
  }
`;

const GridStyles = styled.div`
  display: grid;
  grid-row-gap: 5px;
  padding: 15px 0;
  width: 600px;
  margin: 0 auto 0 0;
  div {
    display: grid;
    grid-template-columns: 100px 1fr;
    align-items: center;
  }
`;

const AddFormStyles = styled.form`
  display: grid;
  grid-template-columns: 1fr 1fr;
`;

const fetcher = (url) => fetch(url).then((r) => r.json());

export default function Form({ formState, setFormState }) {
  const test = formState?.reduce((obj, item, idx) => {
    return { ...obj, [`name-${item._id}`]: item.name };
  }, {});

  const { register, handleSubmit, errors } = useForm({ defaultValues: test });
  const {
    register: register2,
    handleSubmit: handleSubmit2,
    errors: errors2,
  } = useForm();
  const [formStateVals, setFormStateVals] = useState(undefined);
  const [savingState, setSavingState] = useState(false);
  const [deletingState, setDeletingState] = useState(false);

  const { data: formEntryData, error } = useSWR("/api/data", fetcher);

  // console.log(test);

  const onSubmit = async (data) => {
    let hmm = formState.map((ok, i) => {
      //console.log(ok._id);
      var name = data[`name-${ok._id}`];
      var type = data[`type-${ok._id}`];
      var boogie = {
        _id: ok._id,
        name: name,
        type: type,
        index: i,
        arrayOrder: ok.arrayOrder,
      };
      return boogie;
    });

    //1. query all formEntryData *
    //2. Grab all the submitted fields
    //3. run a series of replaces with the correct formEntryData
    //4. as well as the updateField change

    // const letsGo = {
    //   formEntryData,
    //   hmm,
    // };

    // const res1 = await fetch("../api/update", {
    //   method: "POST",
    //   headers: {
    //     "Content-Type": "application/json",
    //   },
    //   body: JSON.stringify(letsGo),
    // });

    // console.log(formEntryData);
    // console.log(hmm);

    hmm.map(async (item, i) => {
      const res = await updateFormInputVal({
        variables: {
          name: item.name,
          type: item.type,
          index: item.index,
          ID: item._id,
          arrayOrder: i,
        },
      }).catch(console.error);
      //console.log(res);
    });
    setSavingState(true);
  };
  //console.log(errors);

  const addInput = async (clickData) => {
    console.log("data");
    console.log(clickData);
    console.log("data");

    const res = await createFormInputVal({
      variables: {
        name: "test",
        type: clickData.chooseType,
        index: 0,
      },
    })
      .then((data) => {
        const blanktext = {
          __typename: "FormInputVal",
          name: "Test",
          _id: data.data.createFormInputVal._id,
          type: clickData.chooseType,
        };
        console.log(blanktext);
        setFormState([...formState, { ...blanktext }]);
      })
      .catch(console.error);
  };

  const deleteVal = async (id) => {
    setDeletingState(true);
    const res = await deleteFormInputVal({
      variables: {
        ID: id,
      },
    }).catch(console.error);
    console.log(res);
  };

  const [createFormInputVal, { data: createInputData }] = useMutation(
    ADD_INPUT_VALUES
  );

  const [
    updateFormInputVal,
    { data: updateInputData, loading: saving },
  ] = useMutation(UPDATE_FORM_INPUT_VAL);

  const [
    deleteFormInputVal,
    { data: deleteInputData, loading: deleting },
  ] = useMutation(DELETE_FORM_INPUT_VAL, {
    refetchQueries: [{ query: INPUT_VALUES }],
  });

  // console.log(updateInputData);

  return (
    <>
      <FormStyles onSubmit={handleSubmit(onSubmit)}>
        <h1>Create Your Form Input Fields</h1>
        <div>
          {formState?.map((val, idx) => {
            const nameId = `name-${val._id}`;
            const typeId = `type-${val._id}`;
            return (
              <div key={val._id}>
                <GridStyles>
                  <div>
                    <label htmlFor={nameId}>Input Name</label>

                    <input
                      type="text"
                      name={nameId}
                      id={nameId}
                      className={val.type}
                      ref={register()}
                    />
                  </div>
                  <div>
                    {val.type}
                    {/* <label htmlFor={typeId}>Input Type</label>

                    <select
                      defaultValue={val.type}
                      name={typeId}
                      ref={register}
                    >
                      <option value="text">text</option>
                      <option value=" image"> image</option>
                    </select> */}
                  </div>
                  <button onClick={() => deleteVal(val._id)} type="button">
                    Delete
                  </button>
                </GridStyles>
              </div>
            );
          })}
          <GridStyles>
            {savingState ? saving ? <p>saving</p> : <p>saved</p> : null}
            {deletingState ? deleting ? <p>deleting</p> : null : null}
            <button type="submit">Save Form</button>
          </GridStyles>
        </div>
      </FormStyles>
      <AddFormStyles onSubmit={handleSubmit2(addInput)}>
        <div>
          <label htmlFor="chooseType">Input Type</label>

          <select name="chooseType" ref={register2}>
            <option value="text">text</option>
            <option value="image"> image</option>
          </select>
        </div>
        <button type="submit">Add Form Inputs</button>
      </AddFormStyles>
    </>
  );
}
从“react”导入{useffect,useState};
从“react hook form”导入{useForm};
从“@apollo/client”导入{useQuery,gql,useVaritation};
从“uuid”导入{v4 as uuidv4};
从“样式化组件”导入样式化;
从“./pages/formBuilder”导入{INPUT_VALUES};
从“下一个/链接”导入链接;
从“swr”导入useSWR;
const ADD_INPUT_VALUES=gql`
变异AddInputValues($name:String!,$type:String!,$index:Int!){
createFormInputVal(数据:{name:$name,index:$index,type:$type}){
名称
类型
指数
_身份证
}
}
`;
常量更新形式输入值=gql`
突变更新最终值(
$name:String!
$type:String!
$index:Int!
$ID:ID!
$arrayOrder:Int
) {
updateFormInputVal(
id:$id
数据:{name:$name,type:$type,index:$index,arrayOrder:$arrayOrder}
) {
名称
类型
指数
安排人
}
}
`;
const DELETE_FORM_INPUT_VAL=gql`
突变DeleteFormInputVal($ID:ID!){
deleteFormInputVal(id:$id){
名称
}
}
`;
const FormStyles=styled.form`
显示:网格;
网格模板柱:350px 1fr 1fr;
标签{
//背景:红色;
}
输入,
挑选{
//背景:水;
边框:1px纯灰;
边界顶部:0;
右边界:0;
左边框:0;
}
输入[type=“button”]{
背景:绿色;
边界:无;
边界半径:30px;
颜色:#fff;
填充:15px;
宽度:200px;
保证金:0.25px自动;
&:悬停{
光标:指针;
}
}
钮扣{
背景:浅灰色;
填充:15px;
边界:无;
&:悬停{
光标:指针;
}
}
`;
const GridStyles=styled.div`
显示:网格;
网格行间距:5px;
填充:15px0;
宽度:600px;
边距:0自动0;
div{
显示:网格;
网格模板列:100px 1fr;
对齐项目:居中;
}
`;
const AddFormStyles=styled.form`
显示:网格;
网格模板柱:1fr 1fr;
`;
常量fetcher=(url)=>fetch(url);
导出默认函数形式({formState,setFormState}){
常量测试=formState?.reduce((对象,项目,idx)=>{
返回{…obj,[`name-${item.\u id}`]:item.name};
}, {});
const{register,handleSubmit,errors}=useForm({defaultValues:test});
常数{
注册人:注册人2,
handleSubmit:handleSubmit2,
错误:错误2,
}=useForm();
常量[formStateVals,setFormStateVals]=useState(未定义);
const[savingState,setSavingState]=useState(false);
const[deletingState,setDeletingState]=useState(false);
const{data:formEntryData,error}=useSWR(“/api/data”,fetcher);
//控制台日志(测试);
const onSubmit=async(数据)=>{
让hmm=formState.map((好的,i)=>{
//控制台日志(ok.\U id);
var name=data[`name-${ok.\u id}`];
var type=data[`type-${ok.\u id}`];
var boogie={
_id:好的,
姓名:姓名,,
类型:类型,
索引:i,,
安排人:好的,安排人,
};
返回布吉;
});
//1.查询所有formEntryData*
//2.抓取所有提交的字段
//3.使用正确的formEntryData运行一系列替换
//4.以及updateField更改
//常数letsGo={
//formEntryData,
//嗯,
// };
//const res1=wait fetch(“../api/update”{
//方法:“张贴”,
//标题:{
//“内容类型”:“应用程序/json”,
//   },
//正文:JSON.stringify(letsGo),
// });
//console.log(formEntryData);
//console.log(hmm);
hmm.map(异步(项目,i)=>{
const res=等待updateFormInputVal({
变量:{
名称:item.name,
类型:item.type,
索引:item.index,
ID:item.\u ID,
审裁官:我,
},
}).catch(控制台错误);
//控制台日志(res);
});
设置保存状态(true);
};
//console.log(错误);
常量addInput=async(单击数据)=>{
控制台日志(“数据”);
console.log(点击数据);
控制台日志(“数据”);
const res=等待createFormInputVal({
变量:{
名称:“测试”,
类型:单击数据。选择类型,
索引:0,
},
})
。然后((数据)=>{
常量空白文本={
__typename:“FormInputVal”,
名称:“测试”,
_id:data.data.createFormInputVal.\u id,
类型:单击数据。选择类型,
};
console.log(空白文本);
setFormState([…formState,{…blanktext}]);
})
.catch(控制台错误);
};
常量deleteVal=async(id)=>{
setDeletingState(真);
常数res=awai
const { register, handleSubmit, errors, reset } = useForm({ defaultValues: test });

useEffect(() => {
  reset(defaultValues: test);
}, [formState])