NextJS在表单提交中调用API



使用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;
}
}

newsearch.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变量。如果需要将.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;

最新更新