Why isn't the default value displayed in MUI AutoComplete?

import * as React from "react";
import TextField from "@mui/material/TextField";
import Autocomplete from "@mui/material/Autocomplete";

export default function MovieComboBox() {
  const [movieList, setMovieList] = React.useState([]);
  const selectedValue = 1;
  React.useEffect(() => {
    fetch("https://reqres.in/api/users?page=1")
      .then((res) => res.json())
      .then(({ data }) => {
        console.log(data);
        setMovieList(data);
      })
      .catch((err) => console.log(err));
  }, []);

  return (
    <Autocomplete
      disablePortal
      id="movie-combo-box"
      defaultValue={
        movieList.find((movie) => movie.id === selectedValue) || null
      }
      options={movieList}
      getOptionLabel={(data) => data.first_name}
      sx={{ width: 300 }}
      renderInput={(params) => <TextField {...params} label="Choose Movie" />}
    />
  );
}

If I remove the if condition, the behavior changes. The defaultValue starts as null and gets updated after fetching the data to display the exact value. However, sometimes the selected value may not show up in the autocomplete box.

Answer №1

Instead of using console.log in the defaultValue, consider utilizing the following method:

value ={top100Films}

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

Step-by-step guide for deactivating the checkbox selection field in the columns menu panel

Incorporating the MUI data grid has been seamless. By simply adding the checkboxSelection attribute to the data grid, checkboxes have been effortlessly implemented for row selection. <DataGridPro sortingOrder={['asc', 'des ...

Another option to innerTheme for customizing primaryTypographyProps in a unique way

I have a unique component with customized list items, icons, and buttons. I need to use this component in two different locations. In the first location, I adjusted the MuiListItemTextTypography props like this... const mainTheme = createMuiTheme({ . . . ...

Are you looking for a search bar to integrate with an external API in a React

I'm encountering an error message stating: 'search' is assigned a value but never used. I am uncertain about whether it is necessary and where it should be placed. Currently, everything functions correctly and the search bar appears above m ...

Using React Testing Library with TypeScript revealed issues with ES6 modules causing test failures

I am currently working on a small project that involves React, Typescript, and Mui v5. The application is relatively small and uses the default Create React App setup. Although I am new to unit and integration testing, I am eager to make use of the tools ...

What is the best way to trigger card opening - through clicking or hovering?

Once the Set tag/status button on the left is clicked, I aim to display a card similar to this one on the right side. What would be the best approach to achieve this in React? Should I use regular CSS, Material UI, or React-bootstrap? https://i.stack.img ...

What steps can be taken to avoid getting caught in an endless cycle of state updates in

When attempting to pass data from a child component to a parent component, I am encountering an issue where the data does not set in the state. An error is thrown when trying to use setState: "Maximum update depth exceeded. This can happen when a componen ...

Customize the text color of a Button in Material UI using themes

Need help with changing button text color directly in Material UI theme. Managed to change primary color and button font size but struggling with text color adjustment. Here's the code: import React from 'react'; import { MuiThemeProvider, c ...

Capture the 'value' of the button when clicked using ReactJS

I'm generating buttons dynamically using the map function to iterate through an array. Each button is created using React.createElement. ['NICK', 'NKJR', 'NKTNS'].map(function (brand) { return React.createElement(' ...

Why is my custom 404 page failing to load after building my Next.js application?

I recently set up a custom 404 page for my Next.js app and wanted to test it locally before deploying to the server. To do this, I used the "serve" package to host the project on my local machine. However, when I tried navigating to a non-existent page, th ...

The React application in VS Code crashes unexpectedly when using the Chrome debugger

Currently, I am facing a challenge while trying to debug a React application using VS Code along with the Chrome debugger extension on my Windows 10 x64 system. Whenever I attempt to log into the application from the login page, the debugger browser unexp ...

The web-pack-dev server is failing to automatically refresh the browser content

As a newcomer to npm and web-pack-dev server, I recently dove into creating a ReactJs app using nmp and webpack. Initially, everything ran smoothly - whenever I saved content, it would automatically refresh and reload in the browser. However, the next da ...

"Learn how to pass around shared state among reducers in React using hooks, all without the need for Redux

I've built a React hooks application in TypeScript that utilizes multiple reducers and the context API. My goal is to maintain a single error state across all reducers which can be managed through the errorReducer. The issue arises when I try to upd ...

Storing data retrieved from a GraphQL response into the sessionStorage: A step-by-step guide

I am facing a challenge in saving my GraphQL response in sessionStorage to access it across different parts of the application without making repeated API calls. I am currently using the useQuery hook with a skip property to check if the data is already st ...

I could use some help understanding how to identify the parent file so I can elevate a state

I'm facing a challenge in lifting up a state so that I can utilize it across various pages. The confusion lies in determining where to reference the states, given the uncertainty regarding the parent location. Since this is my first attempt at designi ...

Exploring the concept of reactive components in ReactJS with nested queries

Updating the query of a component using the setQuery() prop has been challenging for me. The structure of my data is as follows: { root : { category 1: { item 1 {...}, item 2 {...}, }, category 2: { ...

Testing form submission in React with React Testing Library and checking if prop is called

Feel free to check out the issue in action using this codesandbox link: https://codesandbox.io/s/l5835jo1rm To illustrate, I've created a component that fetches a random image every time a button is clicked within the form: import { Button } from " ...

The latest version of Chrome does not store the authentication token in the local session when using msal-browser

I have a Teams React app, but ever since the last Chrome update, I haven't been able to save the authentication token in local session with MSAL. Here is my configuration: MSAL-broswer: 2.38.1 Chrome version: 117 MSAL-configuration: ` { auth: { ...

Personalize the jquery autocomplete outcome

I'm currently utilizing jQuery autocomplete along with a remote data source. $( "input#searchbar" ).autocomplete({ source: function( request, response ) { $.ajax({type: "post", mode: "abort", dataType: ...

Having trouble customizing the active state of a react router navlink using css modules in React?

Objective I am attempting to add styles to the active route in a sidebar using css modules while still maintaining the base styles by assigning 2 classes. This is the code I have tried: <NavLink to={path} className={` ${classes.nav_ ...

How to programmatically close a Bootstrap modal in a React-Redux application using jQuery

Hello everyone, I hope you're all doing well. I am currently working on a React application that utilizes Redux. I have run into an issue while trying to close a modal in Bootstrap programmatically. The versions I am using are Bootstrap 4 and jQuery 3 ...