如何使用 Apollo 和 NextJS 将数据转发到下一页

Tho*_*ore 5 apollo next.js apollo-client react-hooks

我正在使用 NextJS、Apollo 和 React(钩子)开发一个网络应用程序。

我有一个表格,它在注册过程的第一步中询问访问者的姓名。提交表单时,名称将保存在 Apollo 缓存中,访问者将被重定向到下一页。

import React, { useState } from 'react';
import Router , {useRouter}  from 'next/router';
import { useApolloClient } from '@apollo/react-hooks';


const NameForm = props => {
    const [name, setName] = useState("");
    const client = useApolloClient();
    const router = useRouter();

    const handleSubmit = e => {
        e.preventDefault();

        if(!name) return;

        client.writeData({ data: { name } });
        router.push('/user/register');
    }

    return (
        <form onSubmit={handleSubmit}>
            <div>
                <label htmlFor="name">Naam</label>
                <div>
                    <input type="text" id="name" name="name" value={name} onChange={e => setName(e.target.value)} />
                    <button type="submit" onClick={handleSubmit}>Get started</button>
                </div>
            </div>
        </form>
    )
}

export default NameForm;
Run Code Online (Sandbox Code Playgroud)

下一页包含更广泛的表格。当访问者来自主页时,名称已经知道,我想从缓存中取回它。我想

import { gql } from 'apollo-boost';
import { useApolloClient } from '@apollo/react-hooks';
import AddUserForm from '../../components/forms/AddUserForm';

const GET_NAME = gql` 
 query GetName {
    name @client  
}`;

const AddUser = ({ name }) => (
    <React.Fragment>
        <AddUserForm name={name} />
    </React.Fragment>
)

AddUser.getInitialProps = async ctx => {
    const client = useApolloClient();
    const name = await client.cache.readQuery({ query: GET_NAME });

    return { name: name || '' };
}

export default AddUser;
Run Code Online (Sandbox Code Playgroud)

我以为我可以在 getInititialProps 钩子中做到这一点,只允许在功能组件的主体中使用。

由于 next、react hooks 和 apollo 的不断发展,我错过了关于此的教程/课程,我发现很难找到正确的方法来做到这一点。

我希望这里有人可以帮助我进一步。