"Challenges encountered when trying to populate a select field with information retrieved from

I am currently working on a project using NextJS version 13.4.7 with react, and I am facing an issue while trying to update data in a select field with information fetched from an API call. Upon initial page load, I have set a default option field and value for the select field to display instructions to the user.

// Simulating API output
let selectedDistricts = { "data": [{ dist_id: '0', name: 'Select a Province first' }] }

I have created a function that triggers an API call once a different field has selected a value. The problem lies in my attempt to update the selectedDistricts variable with the API data output, resulting in the API returning undefined.

function handleDistricts() {
  console.log('Selected Province ID: ' + passedProvID)
  
  // Issue arises when trying to update selectedDistricts with the API data
  selectedDistricts = GetDistrictsAPI(passedProvID).then(data => {
    console.log('Province District Data: ', data)
    return data;
  });
}

Interestingly, changing the variable name used in the API call to districts resolves the issue and returns the expected data.

function handleDistricts() {
  console.log('Selected Province ID: ' + passedProvID)
  
  districts = GetDistrictsAPI(passedProvID).then(data => {
    console.log('Province District Data: ', data)
    return data;
  });
}

The challenge arises when attempting to populate the select field with the JSON data.

return (
  <Field
    as="select"
    id="pxDistrict"
    name="pxDistrict"
    disabled={!values.pxProvince}
    onChange={(e) => {
      handleDistricts()
      setFieldValue('pxDistrict', e.target.value)
    }}
    className="mt-1 block w-full pl-3 pr-10 py-2 text-base border-gray-300 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm rounded-md"
  >
    {selectedDistricts.data.map((p, i) => (
      <option key={i} value={p.dist_id}>{p.name}</option>
    ))}
  </Field>
)

You can find the full file here. My goal is to avoid creating separate select fields based on different datasets and instead use the same JSON object to map through the option fields within the select element. However, I am struggling to understand why I cannot update the data using the same variable.

I acknowledge that there may be specific features of NextJS 13 or other factors at play here, but I have tried various approaches without success. Any insights or suggestions would be greatly appreciated!

Thank you, Tim

Answer №1

In the code provided, there are a few issues that need attention. To prompt React to reevaluate certain aspects, utilize a state. Additionally, make note of any unused variables. It's crucial to understand that GetDistrictsAPI returns a promise, so simply saving it in selectedDistricts won't suffice – you must execute the code within the "then" block once the API call is complete.

/* eslint-disable react-hooks/rules-of-hooks */
/* TODO: Fix the hook useProvinces inside the useMemo for correct functionality */
import { Field, useFormikContext } from "formik";
import GetDistrictsAPI from "@/_utils/services/GetDistrictsAPI";
import { useState, useEffect, useCallback } from "react";

export default function DisplayDistricts(props) {
  const { setFieldValue, values } = useFormikContext();
  let passedProvID = props.idProvince;

  const [selectedDistricts, setSelectedDistricts] = useState({
    data: [{ dist_id: "0", name: "Select a Province first" }]
  });

  const handleDistricts = useCallback(() => {
    console.log("Province passed = " + passedProvID);
    GetDistrictsAPI(passedProvID).then((data) => {
      setSelectedDistricts(data);
    });
  }, [passedProvID]);

  useEffect(() => {
    handleDistricts();
  }, [handleDistricts]);

  return (
    <Field
      as="select"
      id="pxDistrict"
      name="pxDistrict"
      disabled={!values.pxProvince}
      onChange={(e) => {
        handleDistricts();
        setFieldValue("pxDistrict", e.target.value);
      }}
      className="mt-1 block w-full pl-3 pr-10 py-2 text-base border-gray-300 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm rounded-md"
    >
      {selectedDistricts.data.map((p, i) => (
        <option key={i} value={p.dist_id}>
          {p.name}
        </option>
      ))}
    </Field>
  );
}

Related Links:

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Implement the addition of a numbering column to the MUI data table

I'm trying to figure out how to add a numbering column that displays the row index in my data table. Everything looks great except for the numbering, and I haven't found a solution yet. Here's my code: I have an action column with buttons: ...

Managing Autocomplete Functionality in React with Material-UI, Both with and without a Pre

I am in need of an Autocomplete feature that offers the following functionalities: If the initial value has an id greater than 0, then I want the autocomplete to default to the provided object. If the initial value has an id less than or equal to 0, then ...

Exploring Dynamic Routing using React with Axios and Node.js with Express

My database has 8 tables, each serving as an end-point for different groups. I have multiple routes in my node js/express and sequelize server-side setup to fetch JSON data without having to create separate routes for each table. On the client-side, I&apos ...

The issue of getServerSession() returning null in an API route arises while incorporating NextJs and Next-Auth

Exploring the world of NextJS and Next-Auth has been quite a journey for me. My goal is to create a secure api route that can only be accessed by logged-in users. I've managed to work with session on the client side using useSession(), but when I try ...

Select component experiencing issue with Material Ui label breaking

I've been working on implementing a select component, which is new to me. However, I'm encountering an issue with my MUI-select component. The label of the select element is no longer syncing properly with the select component itself as shown in ...

Created a feature to track the progress of an upload task, but encountered an issue where the item's URL was not being added correctly using this particular

I am looking to implement a progress calculator for tracking the progress of tasks and providing feedback to users. I attempted to accomplish this, but encountered an issue where the URL was not being added to my setUrl(url) hook, causing complications. ...

What is the best way to set breakpoints on Material UI components?

Currently, I am exploring material-ui and I'm curious if there is a way to set all breakpoints at once. The code snippet below seems quite repetitive. Is there a more efficient method to achieve this? <Grid xs={12} sm={12} md={12} lg={12} xl={12} ...

"Discover the step-by-step guide to dynamically generating selects and states in React with the help of Material

Looking to dynamically create Select components based on a list of items? Here's an example: List -> item1, item2 The component : <Select value={this.state."NAME OF THE ITEM ON THE LIST"} onChange={this.handleChange} <MenuItem ...

Using Gmail in conjunction with Heroku for email delivery

After completing an order in my web app, I want to automatically send a confirmation email. I decided to use Nodemailer as it is a popular npm package for this purpose. I successfully coded the functionality and tested it in my local environment. Howeve ...

Caution: React alert for utilizing the UNSAFE_componentWillReceiveProps in strict mode

As a newcomer to React, I encountered a warning that has me stuck. Despite researching extensively online, I still can't resolve it. The warning message is: https://i.stack.imgur.com/4yNsc.png Here are the relevant portions of the code in App.tsx: ...

Enabling table row scrolling with keyboard navigation in React

Struggling to figure out how to make my table scroll while navigating through the rows using the onKeyDown event. It seems that the event isn't updating when using the keyboard, even though the highlighting of the selected row with selected is working ...

Error in custom TypeScript: Incorrect error instance detected within the component

I encountered a unique issue with my custom Error export class CustomError extends Error{ constructor(message: string) { super(message); Object.setPrototypeOf(this, CustomError.prototype); this.name = "CustomError"; } Furthermore ...

Seamlessly incorporating Storybook with Tailwind CSS, Create Next App, and TypeScript

*This is a new question regarding my struggles with integrating Storybook and Tailwind CSS. Despite following the recommended steps, I am unable to make Tailwind work within Storybook. Here's what I've done: I started a TypeScript project from s ...

Are there any solutions to refresh a page by clicking a button in next.js?

I am currently learning how to work with next.js and I'm facing an issue where I need to reload my page to make a new API request. As a beginner, I'm not sure how to achieve this. I've tried a few methods but none of them seem to work. Below ...

Issue with React modal not being visible

I'm having an issue with my code where the delete button is not triggering a modal pop-up when clicked. Although there are no compiling errors, the dev console shows the following warning: Warning:React.createElement: type is invalid--expected a stri ...

Is there a way to identify and count duplicate data-items within an array, and then showcase this information using a react view?

If we have an array like this: [{id: 1, name: "chocolate bar"}, {id:2, name: "Gummy worms"}, {id:3, name:"chocolate bar"}] Is there a way to show on the dom that we have "2 chocolate bars and 1 Gummy Worms"? ...

React - Incorporating Axios catch errors directly within form components

When a user registers, my backend checks if the email and/or username provided are already in use by another user. The response from Axios catch error is logged into the web console. I want to associate each email and username with their respective fields ...

What causes the inversion of height and width settings in react-webcam?

Currently utilizing react-webcam with the following configuration. <Webcam audio={false} screenshotFormat="image/jpeg" videoConstraints={{ facingMode: "environment", width: camera ...

React function causing website to freeze upon dispatch

I created a function in the child component to handle checkbox selection and trigger setDispatch(true). Unfortunately, whenever I check the checkbox, the website freezes and stops responding until I close and reopen it. Here is the function: const [ ...

Tips for maintaining the state in a React class component for the UI while navigating or refreshing the page

Is there a way to persist the selection stored in state even after page navigation? I have heard that using local storage is a possible solution, which is my preferred method. However, I have only found resources for implementing this in functional compone ...