0

Currently I'm trying to run a function that pulls an array of keys from an endpoint. Every time this function is called I want the array on my state to be cleared or reset but it keeps appending to the original. So this.state.keys array just keeps growing larger with every request. I'm brand new to React so please go easy on me.

import React, { Component } from 'react';
import './app.css';
import ReactImage from './react.png';
// import Networks from './Networks/Networks.js';
import Networks from './Networks/Networks.js';
import Button from './Button/Button.js';
import axios from 'axios'

export default class App extends Component {
  state = { 
  networks: [],
  selectedNetwork: "",
  keys: [],
};

getKeys = (networkId) => {
  console.log(this.state)
  fetch('/api/getKeys', {method:'get', headers: {'Access-Control-Allow-Origin': '*'}})
  .then(res => res.json())
  .then(keys => this.setState({
    keys: keys
  }));
}

toggleNetwork = () => {
  this.setState({selectedNetwork: document.querySelector('#funtime').value})
}
componentDidMount() {
  let networkList = [];
  fetch('/api/getNetworks')
    .then(res => res.json())
    .then(networks => this.setState({
      networks: networks.rval
  }));
}

render() {
  return (
    <div>
      {<Networks  toggleNetwork={() => this.toggleNetwork()}
                  networks={this.state.networks}/>}
      <Button state={this.state}
              value={this.state.selectedNetwork}
              clickAction={() => this.getKeys(this.state.selectedNetwork)}
              name="Get Keys"/>
      <img src={ReactImage} alt="react" />
    </div>
  );
}

}

2 Answers 2

1

In your getKeys() do this.setState({keys: []}) on the first line of the function before you make the call to get the new set of keys.

Sign up to request clarification or add additional context in comments.

Comments

0

Issue was with the backend...reseting the setState to a blank array made me realize this but you shouldn't need to do that. setState should overwrite.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.