Home > Back-end >  How to set an interface as the type for a state?
How to set an interface as the type for a state?

Time:01-16

Here is my React functional component that fetches data from an API and stores it in the drinks state.

The data that's fetched is an array of objects. Each object has a key strCategory and a string as its value. So I want to make a TypeScript interface for this data (that's stored in the drinks state). However, I'm not sure where to add that interface (Drink). This is what I'm trying:

function App() {

   interface Drink {
     strCategory:string;
   }

   const [drinks, setDrinks] = useState([{strCategory:''}]) // <---how do I add the interface Drink to this state?

   const fetchData = async () => {
    const response = await fetch('https://www.thecocktaildb.com/api/json/v1/1/list.php?c=list');
    const jsonData = await response.json()
    setDrinks(jsonData.drinks);
  }

  useEffect(() => {
    fetchData()
  }, [])


  return (
    <div className="App">
      <header className="App-header">
        <h2>Drinks</h2>
        {drinks.map((item, index) => {
          return <Link className='App-link' key={index} to="/category?c=">{item['strCategory']}</Link>
        })}
      </header>
    </div>
  );
}

CodePudding user response:

If you inspect the typings of useState, it accepts a generic type that allows you to specify the type of data:

const [drinks, setDrinks] = useState<Drinks[]>([{ strCategory: '' }]);

// Alternatively if you're more comfortable with using Array<...>
const [drinks, setDrinks] = useState<Array<Drinks>>([{ strCategory: '' }]);
  • Related