0

From ResultsTable button click I receive desired value to handleClick function, however setState does not set gameId and remains "", where am I wrong? If I console log gameId it is what I want to have. Thank you for any help.

class ResultsTableContainer extends Component {
 constructor(props) {
 super(props);

this.state = {
  tableConfig,
  games: [],
  gameId: ""
};
}

handleClick = event => {
event.preventDefault();
const gameId = event.target.id;
this.setState({ gameId });
console.log(this.state);
};

currentContent = () => {
if (this.state.gameId !== "") {
  return <GameDetailsContainer gameId={this.state.gameId} />;
}

return (
  <ResultsTable
    tableConfig={this.state.tableConfig}
    games={this.state.games}
    onButtonClick={this.handleClick}
  />
);
};
render() {
 return <div>{this.currentContent()}</div>;
  }
 }

export default ResultsTableContainer;

ResultsTable.jsx

const ResultsTable = ({ games, tableConfig, onButtonClick }) => (
 <Table>
  ...
 <TableBody>
  {games.map((game, index) => (
    ...
        <button>
          <Link
            to={`/games/${game.id}`}
            onClick={onButtonClick}
            id={game.id}
          >
            Results
          </Link>
        </button>
</TableBody>
</Table>
);
export default ResultsTable;
Donatas
  • 25
  • 1
  • 4
  • You need to bind your `handleClick` function. This is the most common reactjs mistake. – jmargolisvt Sep 26 '17 at 15:36
  • 1
    @jmargolisvt: The OP seems to be doing that. They are using the *class fields* proposal with an arrow function. – Felix Kling Sep 26 '17 at 15:37
  • 3
    State is not updated immediately so `this.setState({ gameId }); console.log(this.state);` will log the old state. Do `this.setState({ gameId }, () => console.log(this.state));` instead. – Felix Kling Sep 26 '17 at 15:39
  • I believe setState is an async operation, which accepts a callback method as a parameter. You could try calling console.log in that callback, ensuring it gets called once the setState call is complete. – Daniel Kelley Sep 26 '17 at 15:39

2 Answers2

0

Do not console.log(state) juste after setState. I think everything is working.

Gohmz
  • 1,256
  • 16
  • 31
0

Don't call console right after setState

handleClick = event => {
    event.preventDefault();
    const gameId = event.target.id;
    this.setState({ gameId });
} 
Elumalai Kaliyaperumal
  • 1,498
  • 1
  • 12
  • 24