import React, { Component } from 'react'; import * as ReactDOM from 'react-dom'; import * as queryString from 'query-string'; import PokemonList from '../components/pokemon-list'; import Menu from '../components/menu'; class App extends Component { constructor(props) { super(props); const params = queryString.parse(location.search); const { type } = params; const wantGroupId = params.want_group_id; this.state = { pokemonList: [], selectedPokemon: [], type, wantGroupId, }; } componentDidMount() { fetch('/api/available-pokemon') .then(response => response.json()) .then((data) => { this.setState({ pokemonList: data.pokemons }); }); } render() { const { pokemonList, selectedPokemon, type, wantGroupId, } = this.state; const handleDoneClick = () => () => { const pokemons = []; selectedPokemon.forEach((url) => { pokemons.push({ url, }); }); fetch(`api/stored-pokemon?type=${type}&want-group-id=${wantGroupId}`, { method: 'POST', body: JSON.stringify(pokemons), }).then(() => { if (type === 'want') { window.location.href = '/want.html'; } else { window.location.href = '/index.html'; } }); }; const onSelectPokemon = (selected, url) => { if (selected) { selectedPokemon.push(url); } else { const index = selectedPokemon.indexOf(url); if (index > -1) { selectedPokemon.splice(index, 1); } } this.setState({ selectedPokemon }); }; return ( <div> <Menu /> <PokemonList pokemonList={pokemonList} onSelectPokemon={onSelectPokemon} /> <button type="button" style={{ fontSize: '10em' }} onClick={handleDoneClick()}>Done</button> </div> ); } } ReactDOM.render(<App />, document.getElementById('main'));