0

I have the following App.js file where I try to change 7 state attributes into one easier to manage data object. I am following Updating an object with setState in React trying to use the main answer but I have now tried 3 different ways to update state, including the accepted answer, and nothing is working. I have here App.js:

import React from 'react';

import SearchBar from './SearchBar';
import AllDividendsDisplay from './dividend_results_display/AllDividendsDisplay';
import DividendResultsDisplay from './dividend_results_display/DividendResultsDisplay';

import axios from 'axios';


class App extends React.Component {

  state = {
    loading: false,

    current_price: '',
    recent_dividend_rate: '',
    current_yield: '',
    dividend_change_1_year: '',
    dividend_change_3_year: '',
    dividend_change_5_year: '',
    dividend_change_10_year: '',
    all_dividends: [],
  }

  runStockInfoSearch = async (term) => {
    // clear old data
    this.setState({
      loading: true,

      current_price: '',
      recent_dividend_rate: '',
      current_yield: '',
      dividend_change_1_year: '',
      dividend_change_3_year: '',
      dividend_change_5_year: '',
      dividend_change_10_year: '',
      all_dividends: [],
    });

    // const host = '67.205.161.47';
    const HOST = 'localhost';
    const base_url = 'http://' + HOST + ':8000'
    const dividends_api_url = base_url + '/dividends/' + term

    axios.get(dividends_api_url, {})
      .then(response => {

        console.log(response.data)

        const RESPONSE_KEYS = [
          'current_price',
          'current_yield',
          'recent_dividend_rate'
        ]
        RESPONSE_KEYS.map((key) => {
          this.setState({[key]: response.data[key]})
        })

        this.setState({all_dividends: response.data['all_dividends'].reverse()})

        const YEARS_CHANGE = [1, 3, 5, 10];
        YEARS_CHANGE.map((year) => {
          const key = 'dividend_change_' + year.toString() + '_year';
          this.setState({[key]: response.data[key]})
        });

        this.setState({loading: false})
      })
      .catch(err => {
        console.log(err);
      })
  }

  render() {

    if (this.state.loading === true) {
      return (
        <div className="ui container" style={{marginTop: '10px'}}>
          <SearchBar runSearch={this.runStockInfoSearch} />
          <div className="ui segment">
            <div className="ui active dimmer">
              <div className="ui text loader">Loading</div>
            </div>
          </div>
        </div>
      )
    } else {
      return (

        <div className="ui container" style={{marginTop: '10px'}}>
          <SearchBar runSearch={this.runStockInfoSearch} />
          <DividendResultsDisplay
            current_price={this.state.current_price}
            recent_dividend_rate={this.state.recent_dividend_rate}
            current_yield={this.state.current_yield}
            dividend_change_1_year={this.state.dividend_change_1_year}
            dividend_change_3_year={this.state.dividend_change_3_year}
            dividend_change_5_year={this.state.dividend_change_5_year}
            dividend_change_10_year={this.state.dividend_change_10_year}
            all_dividends={this.state.all_dividends}
          />
        </div>
      )
    }
  }
}



export default App;

I am getting the response data still but cannot update this state to put any data on the screen:

enter image description here

halfer
  • 19,824
  • 17
  • 99
  • 186
codyc4321
  • 9,014
  • 22
  • 92
  • 165

2 Answers2

0

You need to call the constructor function to add a state. For that, change this piece of code:

  state = {
    loading: false,

    dividends_data: {
      current_price: '',
      recent_dividend_rate: '',
      current_yield: '',
      dividend_change_1_year: '',
      dividend_change_3_year: '',
      dividend_change_5_year: '',
      dividend_change_10_year: '',
      all_dividends: [],
    }
  }

with this one:

 constructor(props) {
    super(props);
    this.state = {
    loading: false,
    dividends_data: {
      current_price: '',
      recent_dividend_rate: '',
      current_yield: '',
      dividend_change_1_year: '',
      dividend_change_3_year: '',
      dividend_change_5_year: '',
      dividend_change_10_year: '',
      all_dividends: [],
    }
  };
  }
Youssouf Oumar
  • 29,373
  • 11
  • 46
  • 65
  • yes the issue was calling the wrong attribute of state. your answer helped me in the right direction tho – codyc4321 Aug 04 '22 at 16:09
0

This is the best solution, the simplest way to update a state object:

import React from 'react';

import SearchBar from './SearchBar';
import AllDividendsDisplay from './dividend_results_display/AllDividendsDisplay';
import DividendResultsDisplay from './dividend_results_display/DividendResultsDisplay';

import axios from 'axios';


class App extends React.Component {

  constructor(props) {
    super(props);
    this.state = {
      loading: false,

      dividends_data: {
        current_price: '',
        recent_dividend_rate: '',
        current_yield: '',
        dividend_change_1_year: '',
        dividend_change_3_year: '',
        dividend_change_5_year: '',
        dividend_change_10_year: '',
        all_dividends: [],
      }
    }
  }

  updateStateData = (key, value) => {
    const data = this.state.dividends_data;
    data[key] = value;
    this.setState({data});
  }

  runStockInfoSearch = async (term) => {
    console.log("running search")
    // clear old data
    this.setState({
      loading: true,

      current_price: '',
      recent_dividend_rate: '',
      current_yield: '',
      dividend_change_1_year: '',
      dividend_change_3_year: '',
      dividend_change_5_year: '',
      dividend_change_10_year: '',
      all_dividends: [],
    });

    const HOST = 'localhost';
    const base_url = 'http://' + HOST + ':8000'
    const dividends_api_url = base_url + '/dividends/' + term

    axios.get(dividends_api_url, {})
      .then(response => {

        console.log(response.data)

        const RESPONSE_KEYS = [
          'current_price',
          'current_yield',
          'recent_dividend_rate'
        ]
        RESPONSE_KEYS.map((key) => {
          this.updateStateData(key, response.data[key]);
        })


        this.updateStateData('all_dividends', response.data['all_dividends'].reverse());


        const YEARS_CHANGE = [1, 3, 5, 10];
        YEARS_CHANGE.map((year) => {
          const key = 'dividend_change_' + year.toString() + '_year';
          this.updateStateData(key, response.data[key]);
        });

        this.setState({loading: false})
      })
      .catch(err => {
        console.log(err);
      })
  }

  render() {

    if (this.state.loading === true) {
      return (
        <div className="ui container" style={{marginTop: '10px'}}>
          <SearchBar runSearch={this.runStockInfoSearch} />
          <div className="ui segment">
            <div className="ui active dimmer">
              <div className="ui text loader">Loading</div>
            </div>
          </div>
        </div>
      )
    } else {
      return (

        <div className="ui container" style={{marginTop: '10px'}}>
          <SearchBar runSearch={this.runStockInfoSearch} />
          <DividendResultsDisplay
            data={this.state.dividends_data}
          />
        </div>
      )
    }
  }
}



export default App;
codyc4321
  • 9,014
  • 22
  • 92
  • 165