Rendering an array in React

I'm trying to render my arr in my render function.The code doesn't give any error.Here I'm trying to calculate the fibonacci series and display it on the screen.The problem with the code is when I enter a certain number in the text field it doesn't print the series on the screen but when I clear the text field without refreshing it prints the correct series on the screen.I can't understand where this error comes from.

import React, { useState } from 'react';
import { Button, TextField } from '@material-ui/core';
import './App.css';

function App() {
  const [limit, setLimit] = useState(1);
  const [arr, setArr] = useState([]);

  function handleGenerateFibonacci(event) {
    for (const n of generator(limit)) {
      arr.push(n)
      setArr(arr)
    }
    event.preventDefault();
  }

  function* generator(limit) {
    var i = 0;
    var a = 0;
    var b = 1;
    yield a;
    yield b;
    for (i = 1; i <= limit - 1; i++) {
      var fibNumber = a + b
      yield fibNumber
      a = b
      b = fibNumber
    }
  }



  return (
    <div className="App">
      <form >
        <h1>Generating the Fibonacci Series</h1>
        <h2>Enter the range</h2>
        <TextField onChange={e => setLimit(e.target.value)}></TextField>
        <br />
        <Button onClick={handleGenerateFibonacci} type="submit" style={{
          height: 40,
          width: 160,
          borderRadius: 10,
          backgroundColor: "Blue",
          marginLeft: 50,
          marginRight: 50,
          marginTop: 20,
          fontSize: 16,
          color: "white"
        }} >Calculate</Button>
        <br />
        <h2>Result:</h2>
        <div >
        <p>Fibonacci Series : {"[ " + arr + " ]"}</p>
        </div>
      </form>
    </div>
    
  );
}


export default App;

Upvotes: 1

Views: 110

Answers (2)

Sarun UK
Sarun UK

Reputation: 6756

Try this approach,

function handleGenerateFibonacci(event) {
    for (const n of generator(limit)) {
      setArr((a) => [...a, n]);
    }
    event.preventDefault();
  }

working demo - https://codesandbox.io/s/festive-mayer-xu91t?file=/src/App.js:270-423

Upvotes: 1

Dmitry Reutov
Dmitry Reutov

Reputation: 3032

Because when you click button your code doesn't change value itself, just content of value

function handleGenerateFibonacci(event) {
    for (const n of generator(limit)) {
      arr.push(n)
      setArr(arr)
    }
    event.preventDefault();
  }

...so system doesn't really know that your array has been changed, so better write it this way

function handleGenerateFibonacci(event) {
    for (const n of generator(limit)) {
      arr.push(n)
    }
    setArr([...arr])
    event.preventDefault();
  }

PS when you clean the text field, limit property of state is correctly changing, so system refresh the components

Upvotes: 2

Related Questions