Skip to content

[graphiql] add tab and content through code #4114

@Nils-Schiwek

Description

@Nils-Schiwek

Is there an existing issue for this?

  • I have searched the existing issues

Current Behavior

Hi there,
I want to add a tab add and content to graphiql-react through code.

Here are some code snippets, that should give you an idea:

    <GraphiQL
      fetcher={fetcher}
      defaultEditorToolsVisibility="variables"
      isHeadersEditorEnabled={false}
      plugins={[HISTORY_PLUGIN, explorer]}
      inputValueDeprecation={true}
      initialQuery={query}
      initialVariables={variables}
    >
      <UpdateHashHandler
        newQuerySetter={setQuery}
        newVariablesSetter={setVariables}
      />
    </GraphiQL>

const UpdateHashHandler = ({
  newQuerySetter,
  newVariablesSetter,
}: UpdateHashHandlerProps) => {
  const { addTab, updateActiveTabValues } = useGraphiQLActions();
  const { storage } = useGraphiQL(pick("storage"));

  useEffect(() => {
    const onMessage = (evt: MessageEvent) => {
      // get a message from outside the iframe and parse it 
      const parsed = parseQueryFromMessage(evt.data);
      if (parsed && parsed.query) {
        newQuerySetter?.(parsed.query);
        newVariablesSetter?.(parsed.variables);

        addTab();
        const store = debounce(500, () => {
          storage?.set(STORAGE_KEY.query, parsed.query);
          storage?.set(STORAGE_KEY.variables, parsed.variables);
        });

        const updateTab = debounce(100, (q: string, v: string) => {
          updateActiveTabValues({
            query: q,
            variables: v,
            operationName: "from outside",
          });
        });

        updateTab(parsed.query, parsed.variables);
        store();
      }
    };

    window.addEventListener("message", onMessage);
    return () => {
      window.removeEventListener("message", onMessage);
    };
  }, []);
  return <></>;
};

This somewhat works, as it is parsing the message and opening a new tab with title "from outside", but the content of the ne tab (editor) is empty. I first have to click into an old tab and then back to the new one, then it suddenly is populated.

Expected Behavior

I would expect the function updateActiveTabValues() to update the current tab and immediately show the result.

Steps To Reproduce

No response

Environment

  • GraphiQL Version:
  • OS:
  • Browser: chrome
  • Bundler: npm
  • react Version:
    "react": "18.3.1",
    "react-dom": "18.3.1"
  • graphql Version:
    "@graphiql/plugin-explorer": "5.1.1",
    "@graphiql/react": "0.37.1",
    "graphiql": "5.2.0",
    "graphql": "16.11.0",

Anything else?

No response

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions