Search code examples
reactjsgraphqlnext.jsapollo

next JS apollo Link change clears query, have to refresh page for query to run


I am using Next JS with Apollo and I hve the following query that works just fine, but when I navigate away from the page to another page and back the query doesn't run my fields are empty and I have to hit refresh to populate them. Does anyone know why this may be.

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;

UPDATE: as requested here is the form 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>
    </>
  );
}

Solution

  • We proved (see comments) that data derived from useQuery is logged properly and passed into <Form/> (child component).

    The problem was in not reinitializing form state [managing/helper] hook (useForm). It should be solved with effect:

    const { register, handleSubmit, errors, reset } = useForm({ defaultValues: test });
    
    useEffect(() => {
      reset(defaultValues: test);
    }, [formState])
    

    This hooke resets form state/data on formState prop change.