4

I've done exactly as pointed by the most upvoted answer on this post show or hide element in react.js to show and hide my elements.

But it works only on first button click. If I input another value in my form and resubmit it then the data remains the same as before. It's never going into "Results" second time onwards. What am I doing wrong?

This is the code from that link above:

var Search = React.createClass({
    getInitialState: function() {
        return { showResults: false };
    },
    onClick: function() {
        this.setState({ showResults: true });
    },
    render: function() {
        return (
            <div>
                <input type="submit" value="Search" onClick={this.onClick} />
                { this.state.showResults ? <Results /> : null }
            </div>
        );
    }
});

var Results = React.createClass({
    render: function() {
        return (
            <div id="results" className="search-results">
                Some Results
            </div>
        );
    }
});

ReactDOM.render(<Search />, document.getElementById('container'));

EDIT new code:

module.exports = React.createClass({
    getInitialState: function() {
        console.log("in getInitialState");
        return { showResults: false };
    },
    onClick: function(e) {
        e.preventDefault();
        data = null;
        console.log("in onClick");
        ticId = ReactDOM.findDOMNode(this.refs.ticketid).value;
        if (this.state.showResults == true) // second button click (update data)
        {
            var newdata = "";
            $.ajax({
            url: 'http://localhost:x/' + 'tickets',
            type: 'GET',
            dataType: 'json',
            async: false,
            headers: {
                "Authorization": "Basic " + btoa(u + ":" + p)
            },    
            data: {ticketid: ticId},
            success: function(result) {
                newdata = result.results;
                }
            });

            if(newdata)
            {
                console.log(newdata); //SUCCESS: getting new data here
            }

            this.state.data = newdata; //FAIL: state not getting refreshed
        }

        else
        {
            this.setState({ showResults: true });
        }
    },
    render: function() {
        return (
            <div className='someclass'>
                <form className="someForm" onSubmit={this.onClick}>
                    <input type="text" placeholder = "Enter ticket Id" ref="ticketid" />
                    <input type="submit" value="Find!!" />
                    { this.state.showResults ? <Results /> : null }
                </form>

            </div>
        );
    }
});
90abyss
  • 7,037
  • 19
  • 63
  • 94
  • Could you clarify this `If I input another value in my form and resubmit it then the data remains the same as before.` ? – Oleksandr T. Sep 27 '16 at 05:13
  • So I have a form in my html that takes user input and based on that I make an ajax call to get data into my Results. But what is happening is when the user inputs a value for the first time, everything is working fine. But when the user inputs another value in the searchbox, the result isn't getting refreshed instead it remains the same. – 90abyss Sep 27 '16 at 05:29
  • @90abyss is a component with static text right? What do you expect to see on the second input? – Nevin Madhukar K Sep 27 '16 at 06:54
  • No, above is just a code snippet from the linked post. component in my code basically makes an ajax call based on user input. – 90abyss Sep 27 '16 at 06:57

2 Answers2

0

you need to toggle as

    onClick: function() {
        this.setState({ showResults: !this.state.showResults });
    },
Fazal Rasel
  • 4,446
  • 2
  • 20
  • 31
  • Thanks Fazal. I did this and it works only when I click the submit button twice. In the first click it clears the result displayed and in the second click it actually renders the Result. Anything else I need to add in the onClick function to fix this? – 90abyss Sep 27 '16 at 05:25
  • only toggle `showResults` when there is no `tickets` available. Place an if statement – Fazal Rasel Sep 27 '16 at 05:51
  • Can you please take a look at my edit above? Not sure what's to be done exactly when this.state.showResults == true.. if I make it false then bcoz of that condition in render() null will be displayed. If i do nothing then Results doesn't refresh. How can I make sure Results is refreshed? – 90abyss Sep 27 '16 at 06:39
0

Better to use this:

onClick: function() {
  this.setState(function (prevState) {
    return {
      showResults: !prevState.showResults
    };
  });
}

Source

Nevin Madhukar K
  • 3,031
  • 2
  • 25
  • 52
  • Hey Nevin. Thanks for your reply. The current problem is that the results aren't getting refreshed. I'm able to toggle but the result doesn't get updated when this.state.showResults is already equal to true. Please see my edit above. – 90abyss Sep 27 '16 at 06:56
  • @90abyss I did read. However is a component with static text right? What do you expect to see on the second input? You mentioned - "The current problem is that the results aren't getting refreshed." -> Results is a static component with static text, what do u want to get refreshed within that? – Nevin Madhukar K Sep 27 '16 at 06:57
  • There is an html form which takes user input "ticketid". This ticketid is used by the component to make an ajax call to the server. It returns the formatted results back. So the issue is when the user first comes in and types "123" then everything works well. But when he again searches for another ticket "576" then component is not called. I'm not sure how to update the state of the data – 90abyss Sep 27 '16 at 07:02
  • @90abyss How are you passing the ticketId to the Component? Show that code as well. – Nevin Madhukar K Sep 27 '16 at 07:06
  • I'm basically defining a global variable "ticId" above and using it in different components. I'm updating it using "ticId = ReactDOM.findDOMNode(this.refs.ticketid).value;" If you look at my new edit, I tried to force update the new data but "this.state.data = newdata" isn't working. – 90abyss Sep 27 '16 at 07:23
  • @90abyss Haha, `this.state.data = newdata;` This is not how you update a state. Check my answer. Or just google that. Use setState! – Nevin Madhukar K Sep 27 '16 at 08:23
  • this.setState({ data : newdata }) isn't working either :( i have tried this.replaceState as well but no luck – 90abyss Sep 27 '16 at 08:29
  • @90abyss Woops, I gave the ES6 syntax. Check my answer again. That's the ES5 format. setState is the proper way to update an existing state. Not replace State – Nevin Madhukar K Sep 27 '16 at 08:32
  • @90abyss Still have trouble? If you can create a fiddle, I can maybe debug and fix it for you. – Nevin Madhukar K Sep 27 '16 at 08:32