繁体   English   中英

NextJS 在表单中调用 API 提交

[英]NextJS calling API in a form submit

使用 NextJS,我花了很长时间试图弄清楚如何让应用程序真正调用我在表单提交时设置的 API。 现在,当我点击提交时,我得到一个非常随机的错误,

Error: Search(...): Nothing was returned from render. This usually means a return statement is missing. Or, to render nothing, return null.

您可以假设最终是无用的并且有助于0。我不明白为什么它不起作用,因为它在其他地方的其他组件中起作用。 谢谢您的帮助。 这是我的代码:

api.js


const API = process.env.WP_API_URL;

async function fetchAPI(query, { variables } = {}) {
  const headers = { 'Content-Type': 'application/json' };

  const res = await fetch(API, {
    body: JSON.stringify({ query, variables }),
    headers,
    method: 'POST',
  });

  const json = await res.json();
  if (json.errors) {
    console.log(json.errors);
    console.log('error details:', query, variables);
    throw new Error('Failed to fetch API');
  }

  return json.data;

export async function getCampgroundsByCity(query) {
  const data = await fetchAPI(
    `
    query MyQuery($string: String) {
      campgrounds(where: {city: $string}) {
        nodes {
          acfDetails {
            address
            city
            closeDate
            latitude
            longitude
            numberOfSites
            openDate
            website
            picture {
              altText
              mediaItemUrl
            }
          }
          title
        }
      }
    }
    `,
    {
      variables: {
        string: query,
      },
    }
  );
  return data?.campgrounds;
}

}


新搜索.js:

import { useRouter } from 'next/router';
import { useState } from 'react';
import { ViewportContextProvider } from '../lib/state';
import { getCampgroundsByCity } from '../lib/api';

export default function Search({ viewport, setViewport, cities }) {
  const [view, setView] = useState();

  const handleChange = e => {
    setView(e.target.value);
  };

  const updateViewport = async event => {
    event.preventDefault();

    // const campgroundsbycity = await getCampgroundsByCity('Bethlehem');
    // console.log(view);
  };
  return (
    <form onSubmit={updateViewport}>
      <label htmlFor="city">City</label>
      <select value={view} onChange={handleChange}>
        {cities.nodes.map(town => {
          return (
            <option value={town.acfDetails.city}>{town.acfDetails.city}</option>
          );
        })}
      </select>
      <button type="submit">Submit</button>
    </form>
  );
}

Next.js 以不同的方式工作,具体取决于您构建代码的方式(请参阅此https://nextjs.org/docs/basic-features/data-fetching )。 因此,不同的.env 变量可能会暴露或不暴露。 如果您需要将 a.env 公开(例如 API 调用中的 URL),则必须在名称上使用“NEXT_PUBLIC_”,例如“NEXT_PUBLIC_WP_API_URL”。

您可以在此处阅读有关它的更多信息: https://nextjs.org/docs/basic-features/environment-variables

因此,您必须像这样更改.env:

# OLD
# WP_API_URL=https://my.url.com

# NEW
NEXT_PUBLIC_WP_API_URL=https://my.url.com

你的 api.js 像这样:

// const API = process.env.WP_API_URL;
const API = process.env.NEXT_PUBLIC_WP_API_URL;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM