NextJS calling API in a form submit

sylargaf

using NextJS i'm having a hell of a time trying to figure out how to get the app to actually call a API I have set up upon form submit. Right now I get a very random error when I hit submit,

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

Which as you can presume ultimately is useless and helps 0. I don't understand why its not working though, as it works in other components elsewhere. Thank you for your help. Here is my code:

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>
  );
}

Paulo Carvalho

Next.js works in different ways depending on how you structure your code (see this https://nextjs.org/docs/basic-features/data-fetching ). Because of this, different .env variables might be exposed or not. If you need a .env to be public exposed (like the URL from your API call), you will have to use "NEXT_PUBLIC_" on the name, like this "NEXT_PUBLIC_WP_API_URL".

You can read more about it here: https://nextjs.org/docs/basic-features/environment-variables

So, you'll have to change the .env like this:

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

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

And your api.js like this:

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

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

From Dev

Spring form:select not calling converter on form submit

From Dev

Calling the submit button of the form outside the form in angular

From Dev

calling api does not work nextjs getinitialprops

From Dev

Calling $("#form").submit(... doesn't do anything

From Javascript

Submit form after calling e.preventDefault()

From Dev

JQuery Form Submit Not Calling Controller Method

From Dev

Pass NextJS query arg on submit react-hook-form

From Dev

Trying to map through returned data after a form submit. NextJS

From Dev

window.open createElement('form') with submit input type is not calling the action

From Java

Multiple submit buttons in the same form calling different Servlets

From Dev

Calling JQuery Button Clicks/Form Submit in Firebase Functions and Hosting

From Dev

Why does calling this Javascript function submit my form?

From Dev

jQuery form submit does not work after calling $('#idname').html("");

From Dev

Ajax form submit calling method twice in ASP.NET MVC

From Dev

Submit checkbox form after calling e.preventDefault()

From Dev

Who is the "caller" when calling Form Submit installable trigger?

From Dev

Trying to submit a form from a link while calling a function at the same time

From Dev

Issue with HTML form submit button not calling Google script function

From Dev

Spring Security - Custom login form not calling the AuthenticationProvider on submit

From Dev

submit form with two different Api with condition

From Dev

cypress canceling an api request upon a form submit

From Dev

fetch api happens before I submit the form

From Dev

Validation is skipping when submit the form with rest api

From Dev

Why does calling submit on a form and click on a submit button produce different GET parameters?

From Dev

Calling a PHP API from HTML Form?

From Dev

Form submit to Textarea on submit

From Dev

nextjs errors with form handling

From Dev

Recieveing error when calling api request in NextJs "banner.map is not a function"

From Dev

submit html form with AJAX and display json response from external api

Related Related

  1. 1

    Spring form:select not calling converter on form submit

  2. 2

    Calling the submit button of the form outside the form in angular

  3. 3

    calling api does not work nextjs getinitialprops

  4. 4

    Calling $("#form").submit(... doesn't do anything

  5. 5

    Submit form after calling e.preventDefault()

  6. 6

    JQuery Form Submit Not Calling Controller Method

  7. 7

    Pass NextJS query arg on submit react-hook-form

  8. 8

    Trying to map through returned data after a form submit. NextJS

  9. 9

    window.open createElement('form') with submit input type is not calling the action

  10. 10

    Multiple submit buttons in the same form calling different Servlets

  11. 11

    Calling JQuery Button Clicks/Form Submit in Firebase Functions and Hosting

  12. 12

    Why does calling this Javascript function submit my form?

  13. 13

    jQuery form submit does not work after calling $('#idname').html("");

  14. 14

    Ajax form submit calling method twice in ASP.NET MVC

  15. 15

    Submit checkbox form after calling e.preventDefault()

  16. 16

    Who is the "caller" when calling Form Submit installable trigger?

  17. 17

    Trying to submit a form from a link while calling a function at the same time

  18. 18

    Issue with HTML form submit button not calling Google script function

  19. 19

    Spring Security - Custom login form not calling the AuthenticationProvider on submit

  20. 20

    submit form with two different Api with condition

  21. 21

    cypress canceling an api request upon a form submit

  22. 22

    fetch api happens before I submit the form

  23. 23

    Validation is skipping when submit the form with rest api

  24. 24

    Why does calling submit on a form and click on a submit button produce different GET parameters?

  25. 25

    Calling a PHP API from HTML Form?

  26. 26

    Form submit to Textarea on submit

  27. 27

    nextjs errors with form handling

  28. 28

    Recieveing error when calling api request in NextJs "banner.map is not a function"

  29. 29

    submit html form with AJAX and display json response from external api

HotTag

Archive