0

I am attempting to create a reactJS state that has an empty array in it on construction. Once i receive a message, that is a JSON object, I would want to create a key in that array and store that received message as the value under that key.

for example. I have

array x =[]

JSON_obj = {"data":"mydata"}

in normal javascript I could say

x["some_key"] = JSON_obj

I am attempting accomplish this in reactJS inside the state.

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

    this.state = {
      cusipData: []
    };

    this.socket = io("adresss");

    this.socket.on("ringBuffer", function(data) {
      addMessage(JSON.parse(data));
    });

    const addMessage = data => {
      this.setState({ cusipData: this.state.cusipData[data.cusip], data });

      console.log("this.state");
      console.log(this.state);
    };
  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

2 Answers 2

1

I would be careful with using setState when self-referencing this.state in the method as state should remain immutable. This should work.

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

    this.state = {
      cusipData: []
    };

    this.socket = io("adresss");

    this.socket.on("ringBuffer", function(data) {
      addMessage(JSON.parse(data));
    });

    const addMessage = data => {
      this.setState((prevState, props) => {
        const newCusipData = prevState.cusipData;
        newCusipData[data.cusip] = data;

        return {
          cusipData: newCusipData
        };
      });

      console.log("this.state");
      console.log(this.state);
    };
  }
}
Sign up to request clarification or add additional context in comments.

1 Comment

@SteveBohmbach No problem. If this is solved, can you mark it as well for others looking to accomplish the same thing?
0

The following method addMessage adds the data.cusip parameter to the existing state.cusipData array.

class App extends Component {
  constructor(props)
  {
    super(props)
    
    this.state = {
      cusipData: [],
    };

    this.socket = io("adresss")

    this.socket.on('ringBuffer', function(data){
        addMessage(JSON.parse(data));
    });

    const addMessage = data => {
      // adds the new data.cusip to the existing state array
      this.setState({
        cusipData: [...this.state.cusipData, data.cusip]
      });
    };
  }

1 Comment

I needed to add if not there, and update if it already exsists

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.