After changing input, array add duplicates, but it should not. React

My code:

import React, { useState } from "react";
import { TextField } from "@mui/material";
import { Autocomplete } from "@mui/material";
const App = () => {

  const [myOptions, setMyOptions] = useState([]);
  const getDatafromAPI = () => {
    console.log("Getting data from API...");

    fetch('https://jsonplaceholder.typicode.com/users/').then((response) => {
      return response.json()
    }).then((res) => {
      console.log(res)
      for (let i = 0; i < res.length; i++) {
        console.log(res[i].name)
        myOptions.push(res[i].name)
      }
      setMyOptions(myOptions)
      console.log(myOptions)
    })
  }

  return (
    <div style={{ marginLeft: '40%', marginTop: '60px' }}>
      <h3>Hello, This is my react search bar</h3>
      <Autocomplete 
      style={{ width: 500 }}
      freeSolo
      autoComplete
      autoHighlight
      options = {myOptions}
      renderInput={(params) => (
      <TextField {...params}
      onChange={getDatafromAPI}
      variant='outlined'
      label='Search some things'
      />
      )}
      />
    </div>
  )
}
export default App;

Each time when I enter symbol, my component make request to API and add response to array.
When I entered one letter,here is should be 10 elements. it’s ok.
But if I entered 2 or more symbols.Array add duplicates. it’s bad

How to fix it?

>Solution :

You’re never creating a new array, always just adding to an existing array:

myOptions.push(res[i].name)

This is also mutating state, which you should never do in React.

If you want the results to be an entirely new array, make them an entirely new array and update state with that array. For example:

fetch('https://jsonplaceholder.typicode.com/users/').then((response) => {
  return response.json()
}).then((res) => {
  setMyOptions(res.map(r => r.name));
})

In this case .map() simply projects the results into the list of "name" values and returns that array, which is being used to update the myOptions state.

Leave a Reply